Challenge Modification Question


So I got the challenge completed as stated in the book but I decided to add a part where the portfolio also tells you which StockHoldings are in the portfolio (it keeps the names in a separate NSMutableArray). I know I’m close but I’m running into an issue.

My StockHolding.h

[code]// StockHolding.h

#import <Foundation/Foundation.h>

@interface StockHolding : NSObject
float purchaseSharePrice;
float currentSharePrice;
int numberOfShares;
NSString *name;

@property float purchaseSharePrice;
@property float currentSharePrice;
@property int numberOfShares;
@property NSString *name;

  • (float)costInDollars;
  • (float)valueInDolars;


All I did was add an instance variable so that I could initialize a StockHolding (named stock for example), set a name for it (like “IBM”), and then just do [stock name] and it would return a string of its name, IBM (worked perfectly for the challenge from ch. 18). The issue that I am running in to is with this challenge is that in Portfolio.m when I add a StockHolding to the portfolio I am trying to just have it add a name (NSString object) to the NSMutableArray stockNameList. However then when I check to make sure things were added correctly it is telling me the count is 0 and when I print the array it gives me null. Also, I am getting the names to print out with: NSLog(@“this stock name is: %@”, [s name]);


[code]// Portfolio.m

#import “Portfolio.h”

@implementation Portfolio

@synthesize stockNameList, numStocks;

  • (void)addStockHolding:(StockHolding *)s
    if (!stockList) {
    stockList = [[NSMutableArray alloc] init];
    [stockNameList addObject:[s name]];
    [stockList addObject:s];
    NSLog(@“this stock name is: %@”, [s name]);
    NSLog(@" %@",[stockNameList objectAtIndex:0]);
    NSLog(@" number of stocks: %lu", (unsigned long)[stockNameList count]);

  • (unsigned int)valueOfStocks
    unsigned int sum = 0;
    for (StockHolding *s in stockList) {
    sum += [s valueInDolars];
    return sum;


Anyone have a clue why my names aren’t getting added to the array?


The obvious question to ask is “Have you created the stockNameList array?”


:open_mouth: I completely forgot that putting it in the header doesn’t actually initialize it. I guess this is what I get for my main language being Python. Thanks for this obvious answer. Dang.

Made the following addition…and obviously it worked.

if (!stockNameList) { stockNameList = [[NSMutableArray alloc] init]; } [stockNameList addObject:[s name]];


Now is the perfect time to learn a real programming language such as C, C++, Objective-C or even Lisp. :slight_smile:


Haha yeah, that’s why I’m learning Obj-C.