Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSAutoreleasePool. When is it appropriate to create a new autorelease pool?

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

like image 983
dugla Avatar asked Mar 06 '11 21:03

dugla


People also ask

What is an Autorelease pool?

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.

What is pool in Objective C?

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++) {

What is Autoreleasepool Swift?

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.


2 Answers

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.

like image 113
ughoavgfhw Avatar answered Oct 04 '22 23:10

ughoavgfhw


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.

like image 37
Caleb Avatar answered Oct 04 '22 21:10

Caleb