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
An autorelease pool stores objects that are sent a release message when the pool itself is drained. Important. If you use Automatic Reference Counting (ARC), you cannot use autorelease pools directly. Instead, you use @autoreleasepool blocks.
A pool is created at the first brace and is automatically drained at the end of the scope. Any object autoreleased within the scope is sent the release message at the end of the scope. Let's take a look at this example: for (int i = 0; i < 100000; i++) {
Memory management in swift is handled with ARC (= automatic reference counting). This means that active references to objects are counted and objects are released when they aren't referenced anymore.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With