iphone - 对象死后的生命(保留计数 = 0)

标签 iphone objective-c cocoa cocoa-touch

我刚刚在一些已经运行了几个月的代码中注意到了这一点。虽然这让我很好奇,但我确信我们一直在借来的时间生活......

假设activeItem:

@property (nonatomic, retain) ItemView *activeItem;

我们在touchesEnded中有这个条件:

if (CGRectContainsPoint(dropRect, touchLocation)) {
    ItemView *replacementItem = [[ItemView alloc] initWithFrame:frame];

    [newItems replaceObjectAtIndex:[newItems indexOfObject:activeItem] withObject:replacementItem];

    [self addSubview:replacementItem];
    [controller.view.subView addItem:activeItem];
    [replacementItem goCenter];
    [replacementItem release];
}

唯一保留activeItem的是NSArray,newItems。我是否应该在调用 replaceObjectAtIndex 之前保留它,然后在释放 replacementItem 时释放它?另一种方式?

看起来工作正常,但这不是 EXC_BAD_ACCESS 之前的时间问题吗?!?

最佳答案

我的猜测是,你在某个地方有 activeItem = some 而不是 self.activeItem = some

区别在于“self”点版本通过合成的变元(setter)方法,该方法将在分配给 ivar 之前执行保留。这假设您有一个合成方法或手动构建的方法,可以执行属性声明的操作。

但这可能没有任何区别,因为您可能只是将其用作弱引用。如果您确实想要弱引用,您可能需要更改保留以分配并阅读 Objective-C 弱引用约定。

(在这种情况下,您使用的 activeItem 更像是某物的索引,而不是设计用于“拥有”该对象的“容器”,这使其成为弱如果这就是您的目的,请引用。)

关于iphone - 对象死后的生命(保留计数 = 0),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2114806/

相关文章:

iphone - 如何在单击按钮时显示 UISplitViewcontroller

macos - Swift: undefined symbol :iTunesApplication

iPhone - 删除呈现的 View Controller

iphone - Cocos2D中的坐标系

ios - UIBezierPath - 起伏/嘈杂数据的平滑图表

ios - 有什么方法可以打开这个 Xcode 项目?

ios - 表格 View 单元格无法进入 numberOfRowsInSection

iphone - 如何合并两个 mp3 文件 iOS?

macos - 识别 controlTextDidEndEditing 的发送者

xcode - 如何在 cocoa 应用程序 xcode 中导入和导出本地化文件以便其他人可以翻译它?