|Home » Learning Curve
Memory management Cocoa style.
Unlike Java, Objective-C does not have automatic garbage collection. Java freaks think their memory management is good; others peeking in from other languages don't see things as being that simple, often pointing to the lack of flexibility and more often the inefficiency in such a scheme.
Objective-C doesn't use anything like that at all, meaning there is greater emphasis on proper memory management on the part of the programmer. Yet adhering to the rules and the ideas behind Objective-C memory management is not difficult.
The Golden Rule
The golden rule of Objective-C memory management is that you are responsible for objects you create or retain and must not assume responsibility for objects that you do not create or retain.
Creating objects with Objective-C is always done with one of the following methods.
If you use any of the above methods to create or retain an object, you must eventually release it.
There is an easy way to establish memory cleanups with Objective-C: the autorelease pool. Autorelease pools work inside an autorelease context or scope.
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
/* Create objects */
Objects you create inside such a context will not automatically be released by the autorelease pool: instead you use the autorelease method.
NSObject *someObject = [[[NSObject alloc] init] autorelease];
The autorelease method will find the autorelease pool automatically, and when the pool is released, all objects in it will be released as well.
The Cocoa frameworks automatically set up an autorelease pool at the start of an event loop and release it at the end. Any autoreleased objects you create inside the event loop are automatically released when your methods return.
The Rules, Explicitly
- If you allocate, copy, or retain an object, you are are responsible for releasing it with release or autorelease.
- If you receive an object you did not allocate or copy, you must retain it or copy it if you want to continue using it; otherwise the object will be released at the end of your method code and it is valid as long as control flow remains in your code.
- Use the autorelease method when you want to return an object you will no longer reference; otherwise, for performance reasons, use release.
For further information, see Apple's documentation, both online and with the ADC developer kit, and visit the Cocoa Programming website.