如何将对象添加到数组?

Jos*_*osa 0 cocoa cocoa-touch objective-c uitableview ios

我正在使用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];
Run Code Online (Sandbox Code Playgroud)

Kre*_*iri 7

这条线是这样的:

_selectedThingArray = [[NSMutableArray alloc] init];
Run Code Online (Sandbox Code Playgroud)

每次"尝试添加对象"时执行?如果是,那么这就是你的问题.您可以将其替换为全新数组,并将对象添加到此新数组,而不是将对象添加到现有数组.

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