ios - NSMutableArray 对象所有权

标签 ios objective-c nsmutablearray uitableview

我在 TableViewController 中有 NSMutableArray 来保存项目,这些项目显示在 TableView 中。 NSMutableArray 正在 viewDidLoad 方法中填充。

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self populateItems];
}
- (void)populateItems {
    for (int i = 0; i < numberOfItems; i++) {
        Item *item = [Item createItem];
        [self.items addObject:item];
        item = nil;   // to ensure that newly created object is not pointed by item and only owned by NSMutableArray
    }
}

现在在方法中移动索引之间的行
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
    Item *item = [self.items objectAtIndex:fromIndexPath.row];

    [self.items removeObjectAtIndex:fromIndexPath.row];

    [self.items insertObject:item atIndex:toIndexPath.row];

    [self.tableView reloadData];
}

在这种方法中,我从 NSMutableArray 获取对象并从 NSMutableArray 中删除该对象,然后再将其插入数组。

我的问题是——
如果 NSMutable 是其中对象的唯一所有者
然后从数组中删除它之后,应该没有人指向项目对象。
因此它应该被释放,但事实并非如此。它再次成功插入到 tableview 中。为什么它没有发生。

我相信行 Item *item = [self.items objectAtIndex:fromIndexPath.row];
项目指针不是 fromIndexPath 中存在的对象的所有者

最佳答案

以下行声明了对该对象的强引用。

Item *item = [self.items objectAtIndex:fromIndexPath.row];

这允许您将其从数组中删除并再次插入。

如果由于某种原因您希望 item 不是强引用,您可以这样做:
_weak Item *item = [self.items objectAtIndex:fromIndexPath.row];

关于ios - NSMutableArray 对象所有权,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24112207/

相关文章:

ios - NSURLSession + 带有自签名证书的服务器

ios - 没看懂swift编程中initialize的过程

objective-c - UIManagedDocument 和其他内容

iOS归档应用面临的问题

ios - 在iOS中禁用tableview中的多选单元格

xcode - 访问我的自定义对象中的 NSMutableArray

IOS 和 Objective C - 如何在 Tableview 的 NSUserDefaults 中显示 NSDictionaries 的 NSMutableArray?

ios - UIViewController 没有接收到 TouchBegan 消息

ios - 来自 appStoreReceiptURL 的应用程序内购买 Objective C 状态

ios - 从多维 NSDictionary 的子字典值创建排序数组