我使用来自NSMutableArray的数据填充了一个tableview,一切正常。当我选择一个单元格(didSelectRowAtIndex)时,该项目将从数组中删除,正如它应该做的那样。现在我希望在另一个NSMutableArray中添加这个完全相同的对象。
简而言之:从数组01中删除所选对象,并将所选对象添加到数组02。
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[_array01 removeObjectAtIndex:indexPath.row];
[_array02 addobject?????];
}
答案 0 :(得分:2)
在将对象从第一个数组中删除之前,需要将该对象添加到第二个数组中。以下是使用两行代码执行此操作的方法:
[_array02 addObject:[_array01 objectAtIndex:indexPath.row]];
[_array01 removeObjectAtIndex:indexPath.row];
在一个更复杂的情况下,您可能需要对该对象执行某些操作,您可以改为获取对该对象的引用并将其移动到另一个数组,如下所示:
id myObject = [_array01 objectAtIndex:indexPath.row];
[myObject setTitle:@"new title"]; // example of modifying the object before moving it
[_array02 addObject:myObject];
[_array01 removeObjectAtIndex:indexPath.row];
请注意,在此处的第二个示例中,根据Objective-C内存管理规则,您不是myObject
的所有者。你只需要参考它。 myObject
实际上归_array01
所有,然后_array02
。