NSMutableArray and ARC



我正试图用以下代码将一个对象添加到NSMutableArray中:

Item *newItem = [[Item alloc] init];
[self.theArray addObject:newItem];

如果我没有记错的话,在旧的保留/发布时代,我不必担心newItem变量超出范围,因为当对象被添加到数组时,它会收到retain,因此不会被释放。

但我现在使用ARC,对象消失了。数组本身很好,它已经包含的其他对象不受影响。因此,我怀疑由于某种原因,我的newItem正在自动解除分配。

有人能告诉我这里发生了什么,以及我如何解决它吗?

Item *newItem = [[Item alloc] init];
// This line is the same as this
//
// __strong Item *newItem = [[Item alloc] init];
//
// the newItem variable has strong reference of the Item object.
// So the reference count of the Item object is 1.
[self.theArray addObject:newItem];
// Now theArray has strong reference of the Item object.
// So the reference count of the Item object is 2.

Item对象的引用计数为2,因此不会释放Item对象。如果您的代码具有如下范围,

{
    Item *newItem = [[Item alloc] init];
    [self.theArray addObject:newItem];
}

它不会影响Item对象。

{
    Item *newItem = [[Item alloc] init];
    [self.theArray addObject:newItem];
    // the reference count of the Item object is 2 as I said.
}
// The scope of the newItem variable was ended.
// So the lifetime of the newItem variable was ended,
// then the strong reference by the newItem was gone.
// Thus the reference count of the Item object was reduced from 2 to 1.

Item对象的引用计数为1,因此Item对象也不会被释放。

我终于发现了问题所在。这与拨款无关。发生的情况是,当重新加载表视图时,再次调用wakeFromNib方法。当然,这会重置各种东西,让它们消失。

最新更新