如何正确释放对象?
我知道在 iOS 5 中有自动引用计数,它消除了所有这些的需要,但无论如何它非常简单。
在释放对象之前将其设置为 nil 是一个好的做法,还是反之亦然,先释放它然后将其设置为 nil?
不管怎样,我只是想摆脱我的应用程序中任何崩溃的可能性,我只是想用这种方式来防止它。
谢谢!
I know that in iOS 5 there is automatic reference counting which takes away the need for all of this but it is very simple anyway.
Is it good practice to set an object to nil before you release it or is it vice versa where you release it then set it to nil?
Anyway, I just want to get rid of any possibilities of crashes in my app and I just want this way to prevent it.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
对 nil 调用
release
不会产生任何效果。Calling
release
on nil accomplishes nothing.当您使用自动引用计数时,您无法调用
release
。这样做是一个编译器错误。在手动引用计数中,您应该
release
,然后设置为nil
。将变量设置为nil
,然后调用release
会泄漏对象(不会释放它)。它不会崩溃,但会消耗内存(最终可能会占用太多内存,导致操作系统将您关闭)。ARC 绝对是帮助您减少崩溃的最佳工具。没有任何机制可以消除所有崩溃的可能性。但两个非常简单的规则会有所帮助:
还有许多其他较小的规则,但这是每个 iOS 开发人员都应该开始的两条规则。
When you use automatic reference counting, you cannot call
release
. It is a compiler error to do so.In manual reference counting, you should
release
and then set tonil
. Setting a variable tonil
and then callingrelease
leaks the object (it does not release it). It won't crash, but it will eat memory (eventually possibly so much memory that the OS will shut you down).ARC is your absolute best tool for helping reduce crashes. There is no mechanism that can remove all possibilities of crashes. But two very simple rules will help:
There are many other smaller rules, but those are the two that every iOS developer should start with.
不,在释放对象之前,不要将其设置为 nil,如果将其设置为 nil,基本上你会丢失指向对象的指针,现在你的变量指向 nil。将 release 发送到 nil 不会执行任何操作。如果你想保护自己免受垃圾值/指针的影响,可以在释放对象后将其设置为 nil。但是,我不明白为什么你需要将它设置为 nil,除非它是一个实例变量。
No, you don't set it to nil before you release the object, if you set it to nil, basically you lose pointer to your object, and now your variable is pointing to nil. Sending release to nil does nothing. If you want to protect yourself from garbage value / pointer, you can set it to nil, after you release the object. But, I don't see why you need to set it to nil other than if it's an instance variable.