2013-08-25 203 views
0

我正在使用NSMutableArray填充我的tableview中的單元格。問題是,當我嘗試將一個對象添加到我的數組中時,它將所有對象替換爲已添加的對象,所以我總是隻有一個對象在我的數組中。正因爲如此,每當調用下面的方法時,我的tableview總是隻有一個單元格被覆蓋。我錯過了什麼嗎?如何將對象添加到數組?

_selectedThingArray = [[NSMutableArray alloc] init]; 

_currentThing = newThing; 
//Note: newThing is the object being passed when this method is called. 
//It is the new data that will should passed into the cell. 

[_selectedThingArray addObject:_currentThing]; 

NSLog(@"%@", newThing); 
NSLog(@"array: %@", _selectedThingArray); 

[self.tableView reloadData]; 
+0

你確定你不在你的代碼中的其他地方修改你的數組嗎? – NightFury

+0

我認爲你只是在添加對象的方法中重新創建數組... _selectedThingArray = [[NSMutableArray alloc] init]; ,將創建移動到初始化方法 –

+0

每次調用上述操作時,都會啓動'_selectedThingArray'。奇怪的是,這意味着它只會包含一個項目。 –

回答

2

添加這一點,如果條件分配前:

if(!_selectedThingArray) 
_selectedThingArray = [[NSMutableArray alloc] init]; 

取而代之的是隻:

_selectedThingArray = [[NSMutableArray alloc] init]; 

一切都將是固定的。

+0

並非全部。但短期內似乎不會失敗。 –

7

這是行:

_selectedThingArray = [[NSMutableArray alloc] init]; 

每次 「嘗試添加對象」 時執行?如果是,那麼這是你的問題。不用將對象添加到現有數組,而是將其替換爲全新數組,並將對象添加到此新數組中。

您需要在「嘗試添加對象」之前的某個位置創建數組,或者在您現在正在執行的同一位置創建數組,但只有在尚未創建數組時纔會創建該數組。