Objective-C设置nil和释放之间的差异 [英] Objective-C Difference between setting nil and releasing
问题描述
我知道在 dealloc
中你可以 [object release];
> viewDidUnload (在UIViewController子类中) self.object = nil
。真正的区别是因为 self.object = nil
(我们假设对象是(nonatomic,retain)
属性)保留 nil
(不做任何操作),然后释放旧值,然后引用计数为0对吧?
I've learned that in dealloc
you do [object release];
but in viewDidUnload
(in a UIViewController subclass) you do self.object = nil
. What is really the difference because self.object = nil
(we're assuming object is a (nonatomic, retain)
property) retains nil
(which does nothing) and then releases the old value and then the reference count is 0 right?
推荐答案
self.object = nil
调用您的setter,将释放旧值,将成员设置为 nil
,可能做其他事情(这是一个方法,所以它可以做任何事情)。 任何东西部分是潜在的危险;请参阅此问题,例如
self.object = nil
calls your setter, which will release the old value, set the member to nil
, and possibly do other things (it's a method, so it could do anything). The "anything" part of that is potentially dangerous; see this question, for example.
[object release]
释放旧值,但将成员保留为现在悬停指针,这是一个很好的食谱的bug。在 dealloc
它没有什么关系,因为指针本身即将消失,但在任何其他情况下,释放一个成员没有设置它是一个非常糟糕的主意到 nil
。
[object release]
releases the old value, but leaves the member as a now-dangling pointer, which is a good recipe for bugs. In dealloc
it doesn't really matter, since the pointer itself is about to go away too, but in any other case it's a very bad idea to release a member without setting it to nil
.
(作为一个旁注,你不应该假设释放一个对象给它一个引用计数0.它释放你的引用,但其他对象可能仍然引用它。)
(As a sidenote, you should never assume that releasing an object gives it a reference count of 0. It releases your reference, but other objects may still have references to it.)
这篇关于Objective-C设置nil和释放之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!