NSAutoreleasePool。什么时候适合创建新的自动释放池?
在 iOS/CocoaTouch 上,我经常看到在方法中创建 NSAutoreleasePool 新实例的代码。我最近在 NSOperation 中看到了一个。
设置 NSAutoreleasePool 新实例的基本规则是什么?为什么这比简单地依赖于 main.m 中创建的预先存在的发布池更好?
谢谢,
道格
On iOS/CocoaTouch I often see code that creates a new instance of NSAutoreleasePool within a method. I recently saw one within an NSOperation.
What are the ground rules for setting up a new instance of NSAutoreleasePool? Why is this preferable to simply relying on the pre-existing release pool created in main.m?
Thanks,
Doug
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以随时使用新的自动释放池,但这并不总是有益的。每当您启动新线程时都需要它,否则该线程中自动释放的对象将被泄漏。在创建和自动释放大量对象的方法中创建新的自动释放池也很常见。例如,如果您有一个循环,在 50 次迭代中每次创建 10 个对象,那么您应该考虑为该方法创建一个自动释放池,如果不是作为循环的一部分,以便为每次迭代创建一个新的对象。
You can use a new autorelease pool whenever you want, but it is not always beneficial. It is required whenever you start a new thread or objects autoreleased in that thread will be leaked. It is also common to create new autorelease pools in a method where you create and autorelease a large number of objects. For example, if you had a loop which created 10 objects in each of 50 iterations, you should consider creating a autorelease pool for that method, if not as part of the loop so that a new one is created for each iteration.
当还没有一个池时(例如在一个新线程中),或者当运行循环中的池不够时(在将运行多次迭代的循环中创建自动释放对象),创建您自己的池,或者当您想要更好地控制您创建的自动释放对象最终何时被释放时。
Create your own pool when there isn't already one in place (such as in a new thread), or when the one in the run loop isn't sufficient (creating autoreleased objects in a loop that will run for many iterations), or when you want increased control over when the autoreleased objects you create are ultimately released.
我在iOS 4.3中进行了测试,执行performSelectorInBackground时需要创建自己的自动释放池。使用 NSOperation 或dispatch_async 时不需要创建。
似乎在iOS >= 5.0中,即使使用performSelectorInBackground,系统也会自动创建自动释放池,所以我找不到需要创建自己的自动释放池的情况。
但无法找到记录的更改。
I tested in iOS 4.3 and you need to create own autorelease pool when execute performSelectorInBackground. You do not need to create when using NSOperation or dispatch_async.
Seems in iOS >= 5.0 the system creates autorelease pool automatically even if use performSelectorInBackground, so I was unable to find a case when you need to create own autorelease pool.
Was unable to find that change documented, though.