自动释放何时真正导致 Cocoa Touch 中的释放?
我知道您需要小心 iOS 上的 autorelease
。 我有一个方法返回调用者需要的对象,因此在这种情况下 - 据我所知 - 我需要发送 autorelease
返回之前被调用者中的对象。
这很好,但是一旦控制权返回到手机(即在处理了我的按钮单击之后),自动释放池似乎就被释放了。 我怀疑事情应该是这样的,但我想知道这种情况的最佳做法是什么。
我已采取从调用者发送一条 retain
消息,以便该对象不会被释放,然后在 dealloc
中显式释放它。
这是最好的方法吗?
I understand you need to be careful with autorelease
on iOS. I have a method that is returning an object it alloc
s which is needed by the caller, so in this situation -- as I understand it -- I need to send autorelease
to the object in the callee before it returns.
This is fine, but once control returns to the phone (i.e. after my button click has been processed) it seems that the autorelease pool is released. I suspect this is how it is supposed to be, but I am wondering what is the best practice for this situation.
I have resorted to sending a retain
message from the caller so that the object is not released and then explicitly releasing it in dealloc
.
Is this the best approach?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
自动释放池通常在运行循环的每次迭代后释放。 粗略地说,每个 Cocoa 和 Cocoa Touch 应用程序的结构如下:
您所描述的是预期的行为。 如果你想保留一个对象超过这个时间,你需要显式保留它。
The autorelease pool is typically released after each iteration of the run loop. Roughly, every Cocoa and Cocoa Touch application is structured like this:
What you describe is the expected behavior. If you want to keep an object around any longer than that, you'll need to explicitly retain it.
使用
autorelease
是在表达:“对象,我不再需要你了,但我会把你交给其他可能需要你的人,所以先别消失。 ” 因此,该对象将保留足够长的时间,以便您从方法返回它或将其传递给另一个对象。 当某些代码想要保留该对象时,它必须通过保留
来声明所有权。请参阅内存管理指南,了解使用时需要了解的所有内容正确地
autorelease
。Using
autorelease
is a way of saying, "Object, I don't want you anymore, but I'm going to pass you to somebody else who might want you, so don't vanish just yet." So the object will stick around long enough for you to return it from a method or give it to another object. When some code wants to keep the object around, it must claim ownership byretain
ing it.See the memory management guidelines for everything you need to know to use
autorelease
correctly.以下是 Apple 内存管理文档中提供的示例:
Here is an examle provided in the Apple Memory Management document:
是的,这是最好的方法。 Autorelease 实际上仅适用于您知道的代码中的交互。 一旦你存储了一个对象,你应该知道持有引用的对象不会消失/超出范围,直到你也完成了该对象,或者你需要保留该对象。
Yes, that's the best approach. Autorelease is really only intended for interactions in code that you know. Once you're storing an object, you should either know that the object that holds a reference will not die/go out of scope until you're also done with the object, or you need to retain the object.
仅保证自动释放的对象将在方法结束后被释放。 毕竟,调用您的方法的方法可以创建自己的池并在您的方法之后立即释放它。
It is only guaranteed that autoreleased objects will be released after the end of your method. After all, the method that called your method could have created its own pool and release it right after your method.