我一直在使用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
的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;
}
感谢您的帮助!
答案 0 :(得分: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];