2011-04-21 47 views
0

我對這個網站和iphone開發新手。我通過幾本不同的書籍和斯坦福大學iOS開發在線課程來學習Objective-C。通過Objective-C中的多種方法將項添加到數組中

當前的項目是建立一個計算器(已經完成),但現在我們必須添加一個數組,跟蹤每個操作數或操作的按下。我試圖通過使用「operationPressed」方法和「setOperand」方法添加一段代碼來完成此操作,但是沒有任何內容添加到數組中。

在我的.h文件中,我宣佈的NSMutableArray * internalExpression的實例變量,這是我的.m文件

- (void) setOperand: (double) anOperand 
{ 
    operand = anoperand; 
    NSNumber *currentOperand = [NSNumber numberWithFloat:operand]; 
    [internalExpression addObject:currentOperand]; 
} 

設定操作工程的代碼,並currentOperand被正確設置(使用的NSLog選中)但沒有任何東西都被添加到NSMutableArray中(也使用NSLog和數組計數方法進行檢查)。

我在想什麼?

謝謝!

+0

你真的創建了一個NSMutableArray的實例並將它分配給伊娃(在'init'或等價的)嗎? – Anomie 2011-04-21 14:35:48

回答

0

聲明NSMutableArray是不夠的,它也必須被實例化。在addObject:調用之前添加此行。

if(internalExpression == nil) internalExpression = [NSMutableArray array]; 
2

如果你的頭文件中有聲明如下屬性:

@property (nonatomic, retain) NSMutableArray *internalExpression; // non ARC 

@property (nonatomic, strong) NSMutableArray *internalExpression; // ARC 

你有一個分配的對象來初始化屬性:

NSMutableArray *myMutableArray = [[NSMutableArray alloc] init]; 
[self setInternalExpression:myMutableArray]; 
[myMutableArray release]; // this line only if you're not using ARC. 

如果只是一個inst ANCE變量,你只需要直接做到這一點:

_internalExpression = [[NSMutableArray alloc] init]; 

請記住,如果你不使用ARC,以釋放對象,當你用它做,或者在類的dealloc方法。

問候。