2012-06-14 12 views
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 

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

感謝您的幫助!

回答

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

此行只分配最後facebook變量,以便applegoogle仍然nil添加內容時給他們。

現在,由於對象 - 動態信息分配給對象,當您嘗試將項目添加到nil變量與[google setNumberOfShares:12]或當你調用[apple costInDollars]不會引發錯誤。

嘗試使用:

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

非常感謝。很好的幫助! –

相關問題