0

I've been using Big Nerd Ranch's Objective-C guide and I'm having trouble displaying all the items in the class I created. For more reference it is the challenge in Chapter 17 about Stocks. I know there are other questions on this problem, but I've checked the corrected code for all the others and the problem still persist. For some reason only the Facebook cost is being displayed. Here's my work: StockHolding.h

#import <Foundation/Foundation.h>

@interface StockHolding : NSObject
{
    float purchaseSharePrice;
    float currentSharePrice;
    int numberOfShares;
}

@property float purchaseSharePrice;
@property float currentSharePrice;
@property int numberOfShares;

- (float)costInDollars;
- (float)valueInDollars;

@end

StockHolding.m

#import "StockHolding.h"

@implementation StockHolding

@synthesize purchaseSharePrice;
@synthesize currentSharePrice;
@synthesize numberOfShares;


-(float)costInDollars
{

    return numberOfShares*purchaseSharePrice;
}


-(float)valueInDollars
{

    return numberOfShares*currentSharePrice;
}


@end

main.m

#import <Foundation/Foundation.h>
#import "StockHolding.h"

int main(int argc, const char * argv[])
{

    @autoreleasepool {

        StockHolding *apple, *google, *facebook = [[StockHolding alloc] init];

        [apple setNumberOfShares:43];
        [apple setCurrentSharePrice:738.96];
        [apple setPurchaseSharePrice:80.02];

        [google setNumberOfShares:12];
        [google setCurrentSharePrice:561.07];
        [google setPurchaseSharePrice:600.01];

        [facebook setNumberOfShares:5];
        [facebook setCurrentSharePrice:29.33];
        [facebook setPurchaseSharePrice:41.21];


         NSLog(@"%.2f.", [apple costInDollars]);
         NSLog(@"%.2f.", [google costInDollars]);
         NSLog(@"%.2f.", [facebook costInDollars]);



    }
    return 0;
}

Thanks for your help!

1 Answers1

1
StockHolding *apple, *google, *facebook = [[StockHolding alloc] init];

This line only allocated last facebook variable so apple and google are still nil when you add items to them.

Now, since Obj-C dynamically dispatches messages to objects, no error is raised when you try to add items to nil variables with [google setNumberOfShares:12] or when you invoke [apple costInDollars].

Try with:

StockHolding *apple = [[StockHolding alloc] init], *google = [[StockHolding alloc] init], *facebook = [[StockHolding alloc] init];
Jack
  • 131,802
  • 30
  • 241
  • 343