Memory Management in iPhone – 3
Before directly getting in to Autorelease pool, lets see a new constructor that generates the autoreleased objects.
Those who have worked with cocoa or coca-touch must have come across the following code:
Line 1:NSString *string = [NSString stringWithCString:”Hello”];
What makes it different from the typical :
Line 2: NSString *stringObject = [[NSString alloc] init];
These methods are called convenience constructors and used for creating temporary objects. Line 1 is equivalent to the following line:
Line 3: NSString *stringObject =[ [[NSString alloc] init] autorelease];
That is, the “convenience constructor” creates an object that is sent an autorelease message. In our case the string created in Line 1. autorelease works by making use of an object namedautorelease pool.So what is autorelease pool?
An autorelease pool is an instance of NSAutoreleasePool.
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
An autorelease pool contains other objects that have received an autorelease message. So, when the autorelease pool is deallocated, it sends a release message to all objects that are contained in them.
Once you send an object an autorelease message or get an object from a convenience constructor, never bother about releasing it.
What happens when you create a second autorelease pool in your application?
Autorelease pools are arranged in stack. When you send a autorelease message, the object is added to the current topmost pool of the current thread.
Why should we go for a another autorelease pool?
In iPhone development context, we might need to create autorelease pool at the following scenarios:
When you spawn a secondary thread, in addition to the main thread of your Application. It is not necessary if this thread call does not involve any cocoa function calls.
If you write a looping logic where you create many temporary objects, you may create an autorelease pool inside the loop to dispose of those objects before the next iteration. This would help reduce the maximum memory footprint of the application.
drain or release:
To release a pool, in a non garbage collected environment, both drain and release serves the same purpose. But Apple suggests us to use drain.