0

我一直在使用 Big Nerd Ranch 的 Objective-C 指南,但无法显示我创建的类中的所有项目。如需更多参考,请参阅第 17 章中关于股票的挑战。我知道这个问题还有其他问题,但我已经检查了所有其他问题的更正代码,问题仍然存在。出于某种原因,只显示了 Facebook 费用。这是我的工作: 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

主文件

#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;
}

谢谢你的帮助!

4

1 回答 1

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

这一行只分配了最后一个facebook变量,所以当您向它们添加项目时apple仍然google如此。nil

现在,由于 Obj-C 动态地将消息分派给对象,因此当您尝试使用或调用时将项目添加到nil变量时不会引发错误。[google setNumberOfShares:12][apple costInDollars]

尝试:

StockHolding *apple = [[StockHolding alloc] init], *google = [[StockHolding alloc] init], *facebook = [[StockHolding alloc] init];
于 2012-06-14T02:16:58.177 回答