2013-08-25 139 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]; 

每次 “尝试添加对象” 时执行?如果是,那么这是你的问题。不用将对象添加到现有数组,而是将其替换为全新数组,并将对象添加到此新数组中。

您需要在“尝试添加对象”之前的某个位置创建数组,或者在您现在正在执行的同一位置创建数组,但只有在尚未创建数组时才会创建该数组。