Challenge Output Question


#1

I’m trying to list all the stocks in the portfolio by overriding the description method.

portfolio.m

[code]#import “Portfolio.h”
#import “ForiegnStockHolding.h”
#import “StockHolding.h”

@implementation Portfolio

  • (void)addStock:(StockHolding *)d
    {
    // Is portfolio nil?
    if (!stockPortfolio) {

      // Create the array
      stockPortfolio = [[NSMutableArray alloc] init];
    

    }
    [stockPortfolio addObject:d];
    }

  • (float)portfolioValue
    {
    // Caclulate total value of portfolio
    float sum = 0;
    for (StockHolding *s in stockPortfolio) {
    sum += [s valueInDollars];
    }
    return sum;
    }

  • (NSString *)description
    {
    for (StockHolding *s in stockPortfolio) {
    return [NSString stringWithFormat:@“Stock purchase: %.2f, current: %.2f, shares: %d”, [s purchaseSharePrice], [s currentSharePrice], [s numberOfShares]];
    }
    return 0;
    }

@end
[/code]

Then calling it in main.m

However, it is only printing the first stock in the list. Is this not the right way to achieve this?


#2

Ok, after having taken the time to post this, I see that when the first value is returned, it exits out. So what would be the RIGHT way of doing this?


#3

You have diagnosed the problem. Now you need to apply the treatment: instead of returning from the for loop, put all descriptions into the same string and return it (from outside the loop, of course.) You can do this easily with an instance of NSMutableString.

- (NSString *)description
{
      NSMutableString *it = [NSMutableString string];
      for (StockHolding *s in stockPortfolio) {
            [it appendFormat:@"Stock purchase: $%.2f, current: $%.2f, shares: %d", [s purchaseSharePrice], ...];
      }
      return it;
}

Make NSMutableString one of your friends and learn all about it.


#4

Had to change “appendStringWithFormat” to just “appendFormat”, but it worked like a charm. Thanks!