gpt4 book ai didi

ios - NSMutableArray 对象所有权

转载 作者:行者123 更新时间:2023-12-01 18:59:06 25 4
gpt4 key购买 nike

我在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com