Cocoa Memory Management
There is no garbage collection in Objective-C (although it possibly will be introduced in Mac OS/X 10.5). Instead, objects have reference counts. They work as follows:
- If an object is allocated, it has a refcount of 1.
- [obj retain] increments the refcount.
- [obj release] decrements the refcount.
- When the refcount reached 0, the object is deallocated.
Next to this, Objective-C employs something called 'autorelease pools'. When an object is created, it registers at the nearest autorelease pool with a counter of 0. Then:
- NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init] creates a pool.
- [obj autorelease] increments the counter in the pool.
- [pool release] releases the pool. For every object registered, [obj release] is called as many times as the counter indicates.
So, this mechanism defers releasing objects. Any object which was otherwise released, is now released when the pool is. This increases efficiency. The following is important:
For every retain, an object should call either release or autorelease.
The reason is obvious: autorelease is just a deferred release call.
If there is no autorelease pool, objects will leak memory, and you will get warnings like:
2006-11-03 09:03:42.924 a.out[26333] *** _NSAutoreleaseNoPool(): Object 0xa370d918 of class NSCFString autoreleased with no pool in place - just leaking
