为什么在 iPhone 的 Three20 中使用 TT_RELEASE_SAFELY?
#define TT_RELEASE_SAFELY(__POINTER) { [__POINTER release]; __POINTER = nil; }
为什么 Three20 认为在释放 ivar 后将其赋值为 nil 是安全的?省略 ivar = nil 步骤是否不安全?
我不认为我正在使用 KVO/KVC,但我不太确定。我现在正在读它。
谢谢!
马特
#define TT_RELEASE_SAFELY(__POINTER) { [__POINTER release]; __POINTER = nil; }
Why is does three20 consider it safe to assign an ivar to nil after releasing it? Is it unsafe to leave out the ivar = nil
step?
This is all I found:
http://github.com/facebook/three20/commit/1b946f475fb28d60e0aafc9ef394050c642c3a5b#commitcomment-115517
I don't think I'm using KVO/KVC, but I'm not really sure. I'm reading up on it now.
Thanks!
Matt
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在
-dealloc
内部,这个问题让 Objective-C 专家产生了分歧。例如,阅读最近的博客条目。当在其他方法的实现中时,我个人的观点是,您不应该首先在发布后将变量保留在范围内。此代码
可能会在稍后的代码中意外访问
someObject
,从而导致崩溃。所以你可能会说这样会更好,因为向
nil
发送消息是无害的。但是,在这种情况下,您可以完全消除危险:
这里我使用
{...}
块来限制变量的范围。那么稍后使用someObject
就只是一个编译时错误。When inside
-dealloc
, this question splits the Objective-C gurus. read this recent blog entry for example.When inside an implementation of other methods, my personal opinion is that you shouldn't keep the variable in scope after the release in the first place. This code
might accidentally access
someObject
later in code, thus leading to a crash. So you might saywould be better, because messaging to
nil
is harmless.However, in this case you can remove the danger altogether:
Here I'm using a
{...}
block to limit a scope of a variable. Then the use ofsomeObject
later is simply a compile-time error.特别是对于在dealloc中释放ivars的情况,社区中有相当多的争论,关于释放后是否将它们设置为nil更好。
支持零的阵营认为,一般来说,在对象被释放后被访问的不幸情况下,甚至在多线程应用程序的情况下,它使应用程序不太可能崩溃。
反零阵营并不认为上述论点特别有用,因为他们认为应用程序应该在这种情况下崩溃,以便更明显地表明您的应用程序有缺陷(它正在访问已释放的对象)。
这不一定是最全面的立场总结,但它让您了解所涉及的“争议”。
KVO/KVC 问题在某种程度上是独立的,因为这不是关于是否将 ivar 设置为 nil 的争论,而是关于使用属性的 setter 这样做是否安全,因为可能存在副作用问题(如 KVO/KVC) 。
In particular for the case of releasing ivars in
dealloc
there is a fair amount of debate in the community about whether it is better to set them tonil
after releasing or not.The pro-nil camp feel that in general it makes the app less likely to crash in the unfortunate case where an object is accessed after being deallocated, or even during in the case of multi-threaded applications.
The anti-nil camp doesn't feel like the above argument is particularly useful because they feel the app SHOULD crash in such a case to make it that much more obvious that your application has a defect (it is accessing a deallocated object).
That's not necessarily the most comprehensive summary of the positions, but it gives you an idea of the "controversy" involved.
The KVO/KVC issue is somewhat separate as that is an argument not about whether to set the ivar to nil, but whether it's safe to use the setter of a property to do so because of possible side-effect issues (like KVO/KVC).