在 Autorelease 上下文之外使用对象
根据 Apple 开发者网站有关自动释放池的文章中的“保证基金会所有权政策” http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmAutoreleasePools.html#//apple_ref/doc/uid/20000047-997594,他们谈论扩展对象的生命周期超出自动释放池。
有人能给我一个可以使用这个概念的情况吗?
under the "Guaranteeing the Foundation Ownership Policy" in Apple developer's site article on Autorelease pool
http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmAutoreleasePools.html#//apple_ref/doc/uid/20000047-997594, they talk about extending an object's lifetime beyond the Autorelease pool.
Can someone give me a situation where this concept could be used?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
简短回答:文档所说的是,如果您需要将已自动释放的对象保留在自动释放池中,则需要保留它。
长答案:例如,假设我需要对 1000 个对象执行某种操作。一旦我完成了这些对象,我将自动释放它们。如果没有自动释放池,它们最终将被释放,但是将这 1000 个对象保留在内存中会使您的程序变得非常慢(至少在它们被自动释放之前)。
为了解决这个问题,我创建了一个自动释放池,每 100 个对象就会清理一次。但是,如果我需要保留最后一批的最后一个对象,会发生什么情况?我还需要清除其他 99 个物体。我要做的就是向最后一个对象发送一条保留消息,然后清理自动释放池。
这样,自动释放池将通知系统它不再需要这 100 个项目,但您已经让系统知道您确实需要其中一个。如果对象之前的保留计数为 1,那么它仍然会是:
1(原始保留计数)+1(您的保留)-1(自动释放池释放)= 1。
这会在自动释放池释放后保留对象。完成了。
Short answer: What the documentation is saying is that if you need to keep an object that has been autoreleased in an autorelease pool, you need to retain it.
Long answer: For instance, say I need to do a certain operation to 1000 objects. Once I'm done with these objects I'm going to autorelease them. Without an autorelease pool, they're going to be eventually released, but holding those 1000 objects in memory can make your program really slow (at least until they're autoreleased).
In order to solve this issue, I'm creating an autorelease pool that will be cleaned every 100 objects. However, what happens if I need to keep the last object of the last batch around? I still need to purge those other 99 objects. What I'm going to do is send a retain message to that very last object then clean the autorelease pool.
This way the autorelease pool will notify the system that it no longer wants those 100 items, but you've already let the system know that you do need one of them. If the object had a previous retain count of 1, then it'll still be around:
1 (original retain count) +1 (your retain) -1 (autorelease pool release) = 1.
This preserves the object after the autorelease pool is done with it.