0

我正在使用 NSMutableArray 填充表格视图中的单元格。问题是,当我尝试将一个对象添加到我的数组时,它会将所有对象替换为添加的对象,因此我的数组中始终只有 1 个对象。因此,每当调用以下方法时,我的 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];
4

2 回答 2

7

这条线是:

_selectedThingArray = [[NSMutableArray alloc] init];

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

您需要在“尝试添加对象”之前的某个时间点创建数组,或者在您现在正在执行的相同位置创建数组,但前提是您尚未创建数组。

于 2013-08-25T13:43:23.473 回答
2

在分配之前添加这个 if 条件:

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

而不仅仅是这个:

_selectedThingArray = [[NSMutableArray alloc] init];

一切都会得到解决。

于 2013-08-25T13:47:05.257 回答