如何将对象添加到数组?

时间:2013-08-25 13:39:03

标签: ios objective-c cocoa-touch cocoa uitableview

我正在使用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];

2 个答案:

答案 0 :(得分:7)

这一行:

_selectedThingArray = [[NSMutableArray alloc] init];
每次“尝试添加对象”时都会执行

?如果是,那么这就是你的问题。不是将对象添加到现有数组,而是将其替换为全新数组,并将对象添加到此新数组中。

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

答案 1 :(得分:2)

在分配前添加此if条件:

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

仅取而代之:

_selectedThingArray = [[NSMutableArray alloc] init];

一切都将得到解决。

相关问题