ARC:retain cycle 导致的一个内存警告问题

来源:互联网 发布:淘宝助理大头笔设置 编辑:程序博客网 时间:2024/06/05 05:22


我有一个 ViewController 类 AdvancedVC,程序里的其他 ViewController 都继承自它。当 didReceiveMemoryWarning发生时,子类的 viewDidUnload (在这个方法中释放属性和实例变量)被调用,然后程序崩溃:

[AdvancedVC isViewLoaded]:Send messages to a dealloaced instance

断点指向了 AdvancedVC 的 didReceiveMemoryWarning 方法。

这样我在父类中不敢将任何属性设置为 nil ,否则程序就会崩溃。这又会导致另一个问题,内存得不到释放,对象会一直存在。

这个问题一直困扰着我。最近在 stackflow 上看到一篇帖子。跟我的问题很类似(http://stackoverflow.com/questions/11612466/didreceivememorywarning-crash):

问题在于父类有一个 custom view,这个 custom view 有一个属性指向了 ViewController。在使用 ARC 时,dealloc方法中 ViewController 会被设置为 nil,这导致程序崩溃。当我在 custom view 中将这个 ViewController 属性删除,问题解决。

这立即启发了我。在我的 custom view 中,也有一个实例变量 superView,指向了 ViewController 的 view。由于默认情况下实例变量为strong,当ViewController 发生 didReceiveMemoryWarning ,custom view 会setNil,并导致superView 也 setNil,接下来在 super viewDidUnload 中 isViewLoaded 调用时,AdvancedVC 的view 已经是 nil 了,导致应用程序崩溃。

于是我将 custom view 中的 superView 实例变量修饰为 __weak,这样当 custom view dealloc时,superView不会被 setNil。问题不再出现。

 

原创粉丝点击