2014-04-07 201 views
0

我有一個很奇怪的問題,我有兩個類,第一個是NSObject類的子類,它包含一個將對象添加到其數組的方法。請參見下面的代碼:NSObject無法訪問屬性和方法

#import "portfolio.h" 

    @implementation portfolio 


    -(void) addStockObject:(stockHolding *)stock 
    { 
     [self.stocks addObject:stock ]; 
    } 

    +(portfolio *) alloc 
    { 
     return [self.superclass alloc]; 
    } 

    -(portfolio *) init 
    { 
     self.stocks=[[NSMutableArray alloc]init]; 
     return self; 
    } 

    -(NSString *)getCurrentValue 
    { 

     stockHolding *stockInArray; 
     float currentValue=0.0; 

     for (NSInteger *i=0; i<[self.stocks count]; i++) { 
      stockInArray = [self.stocks objectAtIndex:i]; 
      currentValue+=stockInArray.currentValue; 

     } 
     return [NSString stringWithFormat:@"Current Value: %f",currentValue]; 
    } 
    @end 

所以當我調用的方法 - (空)addStockObject:(持股*)的股票,我得到以下錯誤(運行時):

Terminating app due to uncaught exception 'NSInvalidArgumentException', 
    reason: '-[NSObject addStockObject:]: unrecognized selector 
    sent to instance 0x8b48d90' 

調用代碼是:

 p=[[portfolio alloc]init]; 
    [p addStockObject:s]; 
    portfolio *p; 

任何人都可以告訴我什麼是錯?

其他類有一個屬性,似乎它不能在編譯期間訪問它。 我真的很困惑。

謝謝 彌撒

+1

請按照命名約定和大寫字母開始課程。例如,您的「投資組合」類應該是「投資組合」。 – NobodyNada

回答

2

首先,永不覆蓋+(portfolio *) alloc

其次,init方法必須調用另一個init方法,並且在設置ivars之前,您必須始終檢查selfnil。 Apple建議不要在init方法中使用屬性來設置ivars,並且init方法應始終在支持它的編譯器中返回instancetype或在不支持的編譯器中返回id

-(instancetype) init 
{ 
    self = [super init]; 
    if (self) 
    { 
     _stocks = [[NSMutableArray alloc] init]; 
    } 
    return self; 
} 
+0

爲'NSObject'的直接子類調用'init'應該不是技術上必要的,只是一個好習慣。然而擺脫'alloc'是關鍵。 –

+0

嗯,我從來沒有聽說過它不需要直接子類。有沒有參考這個副手?就像你說的那樣,這是一個好習慣。 – BergQuester

+0

從'NSObject'文檔:「在NSObject類中定義的init方法不會進行初始化;它只是返回self。」 –