Objective-C 中何时发布的参考
我在 Objective-C 中经常遇到一个问题。我要么发布太多次,要么发布不够。或者也许我没有足够地保留它们......
有人可以给我指出一个很好的参考资料,它可以为我提供何时需要保留和释放的经验法则吗?
例如:
我记得在某处读到有些对象是预先保留的,所以我需要释放它们,但不保留它们。这些是什么物体?
如果我分配一个对象并且只在该方法中需要它,我是否需要释放它?保留它吗?
显然,如果我保留了某些东西,我需要释放它,但除此之外,我会有点迷失。
I'm having a recurring problem in Objective-C. I'm either releasing things too many time, or not enough. or perhaps I'm not retaining them enough...
Can someone point me at a good reference that will give me a rule of thumb on when I need to retain and release?
For example:
I remember reading somewhere that some objects come pre-retained, so I need to release them, but not retain them. Which objects are these?
if I alloc an object and only need it in that method, do I need to release it? retain it?
Obviously, if I retained something, I needtorelease it, but beyond that, I get a bit lost.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
规则通常非常简单。如果您通过以下方式之一获取对象:
那么您需要在某个时刻释放它——通常使用相同的方法或您的dealloc方法。换句话说,使用匹配的
平衡对
调用。alloc
、retain
、copy
和mutableCopy
的调用释放这种情况很少发生。被调用方法的文档应指定您负责释放返回的对象;否则,您应该假设您正在接收一个自动释放的对象。
是的,您需要释放它(但不需要保留它)。 (如果您只想在该方法中使用它,您还可以使用返回自动释放对象的便捷方法之一。)
The rules are generally pretty simple. If you get an object in one of the following ways:
then you need to release it at some point -- in the same method, or your
dealloc
method, generally. In other words, balance your calls toalloc
,retain
,copy
, andmutableCopy
with a matchingrelease
call.This happens rarely. The documentation for the called method should specify that you are responsible for releasing the returned object; otherwise, you should assume you're receiving an autoreleased object.
Yes, you need to release it (but you don't need to retain it). (You can also use one of the convenience methods that return an autoreleased object if you're only going to use it in that method.)
有一个且只有一个规范参考:Apple 的 内存管理Cocoa 或 iPhone 指南。
There is one and only one canonical reference: Apple's Memory Management Guide for Cocoa or iPhone.