concept autorelease pool in category ios

appears as: n autorelease pool, autorelease pool, An autorelease pool, utorelease pools
Objective-C Fundamentals

This is an excerpt from Manning's book Objective-C Fundamentals.

Ideally, you’d have a way to signal to Objective-C that you’re ready for ownership of an object to be released, but instead of relinquishing ownership immediately, you prefer it to be performed at some point in the future, once the caller has had a chance to claim ownership for itself. The answer to this scenario is called an autorelease pool.

To use an autorelease pool, you simply send the object an autorelease message instead of the more immediate release message. This technique is demonstrated by the following version of the CreateMessageForPerson method:

- (NSString *)CreateMessageForPerson:(NSString *)name
{
    NSString *msg = [[NSString alloc] initWithFormat:@"Hello, %@", name];
    [msg autorelease];
    return msg;
}

With the string added to the autorelease pool, you’ve relinquished ownership of the string, yet it’s safe to continue referring to and accessing it until some point in the future when it’ll be sent a more traditional release message on your behalf. But what exactly is an autorelease pool, and when will the string be deallocated?

9.3.1. What is an autorelease pool?

An autorelease pool is simply an instance of the NSAutoreleasePool class. As your application runs, ownership of objects can be transferred to the most current autorelease pool. When an object is added to an autorelease pool, it takes over ownership of the object and sends the object a release message only when the pool itself is deallocated.

9.3.5. Why not use an autorelease pool for everything?

After discovering the concept of autorelease pools, you may wonder why you can’t just add every object to an autorelease pool and avoid the need to carefully match retain and release messages. The answer to this is generally one of performance and memory consumption—two issues that are vitally important on a constrained and typically battery-powered mobile device.

When adding objects to an autorelease pool, you’re ensured that the object will eventually be released on your behalf, but implicitly you also know this will be at some point in the future. Depending on your application logic, these objects could persist for a comparatively long time after you’re done using them—in effect, artificially inflating the memory consumption of your application. This may not be much of a problem on a desktop, but it can be a big problem on a memory-constrained device such as the iPhone. As an extreme case, consider the following code snippet: