iphone - dealloc期间 `self`用法的解释?

标签 iphone objective-c

我试图锁定我对 Objective-C 中正确内存管理的理解。

我已经养成了显式声明 self.myProperty 而不仅仅是 myProperty 的习惯,因为我偶尔会遇到属性不会设置为引用的情况这是我的意图。

现在,我正在阅读有关发布 IBOutlets 的 Apple 文档,他们说所有 socket 都应在 dealloc 期间设置为 nil。因此,我按如下方式进行了设置,结果出现了崩溃:

- (void)dealloc {
    [self.dataModel close];
    [self.dataModel release], self.dataModel = nil;
    [super dealloc];
}

所以,我尝试取出“ self ”引用,如下所示:

- (void)dealloc {
    [dataModel close];
    [dataModel release], dataModel = nil;
    [super dealloc];
}

第二个系统似乎按预期工作。然而,这让我有点困惑。当我认为 self 是一个相当良性的引用时,为什么 self 会在这种情况下导致崩溃,而不是其他任何东西?另外,如果 self 在这种情况下不合适,那么我必须问:什么时候应该包含 self 引用,什么时候不应该包含?

最佳答案

在看到Apple示例代码和iPhone开发书籍后,我采用了以下方法。

在“viewDidUnload”中将导出设置为nil(使用SELF访问器) 在“dealloc”中释放它们(无 SELF)

- (void)viewDidUnload {
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
    self.button = nil
}


- (void)dealloc {
   // no SELF
   [button release];   // UI objects
   [images release];   // model objects
}

关于iphone - dealloc期间 `self`用法的解释?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2999874/

相关文章:

objective-c - 类型类数组的问题

iphone - 关于带有文本字段的 UIAlertView...

iphone - 每秒多次更改 UIButton 背景图像

objective-c - 为什么不设置值:forKeyPath invoked on mutable dictionary throw exception for unknown keypaths?

iphone - Round value iOS 中的浮点值

iphone - 获取动画 UIImageview 的坐标

iphone - 无法从 Xcode 项目中删除启动图像

iphone - 在 iOS 4 中使用 Storyboard和 ARC

iphone - ipad 未调用 didSelectAnnotationView

objective-c - 将 32 位结构传递给 32 位整数函数参数