在dealloc中将IBOutlets设置为nil [英] Settings IBOutlets to nil in dealloc
问题描述
在此处的内存警告部分 http://developer.apple.com/iphone/library/documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmNibObjects.html ,我不明白IBOutlet在dealloc中设置为nil的原因。如果
In the section titled 'Memory Warnings' here http://developer.apple.com/iphone/library/documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmNibObjects.html, I don't follow why the IBOutlet is set to nil in the dealloc. If
self.anOutlet = nil
导致主题中提到的崩溃,为什么他们将ivar设置为nil?
causes a crash as mentioned in the topic, why are they setting the ivar to nil?
一般来说, $ $> $>
In general, why would you set an ivar to nil in the dealloc when you are already calling release?
推荐答案
c $ c>,指针本质上无效,并再次访问可能会导致崩溃。通过在 release
后设置一个变量 nil
,可以防止发生崩溃。
After a release
, the pointer is essentially invalid and accessing it again may cause a crash. By setting a variable to nil
after release
you prevent that crash from happening. There's no harm in accessing a nil pointer.
您链接的示例简单地说明了为什么将变量或ivar设置为 nil
之后 release
,即使看起来像变量/ ivar将不会被再次访问。
The example you've linked to simply demonstrates why it's always a good idea to set a variable or ivar to nil
after release
, even when it looks like the variable/ivar won't be accessed again.
在示例中, anOutlet
ivar实际上是由 dealloc
方法,所以如果你不设置为nil,你会得到一个崩溃。像这样的情况很难通过查看代码,所以这是一个好主意nil每个变量释放后,即使在dealloc。
In the example, the anOutlet
ivar is actually accessed by the superclass after your dealloc
method, so if you don't set it to nil you will get a crash. Scenarios like that are very hard to spot just by looking at the code, so it's a good idea to nil every variable after release, even in dealloc.
这篇关于在dealloc中将IBOutlets设置为nil的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!