问题
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
回答1:
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.
回答2:
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.
回答3:
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.
来源:https://stackoverflow.com/questions/5213588/nsautoreleasepool-when-is-it-appropriate-to-create-a-new-autorelease-pool