Cocoa is a set of frameworks for Macintosh application development. With the news that Apple will be shipping an Intel version of Mac OS X, understanding the Cocoa environment has gained importance for a broad new range of software developers. In this article, I examine Cocoa memory management. Applications that efficiently manage memory tend to load faster, exhibit better performance (especially in low-memory situations), and are less susceptible to errors caused by memory leaks and fragmentation. The code examples I present hereincluding MemLab, an application that lets you explore memory-management conceptswere developed and tested with Apple's Xcode IDE. MemLab requires a PowerPC Macintosh running Mac OS 10.3 (or later).
Cocoa uses a memory-management scheme that's different from that of Java or C++. For instance, when instantiating a new object in C++, you use
theObj = new theClass;. You can later dispose of that object with
delete theObj;. In Java, however, you instantiate a new object with
theObj=new theClass();. You then take no action to dispose of the object. Instead, Java's garbage collection decides when to dispose of the object.
Cocoa takes an intermediate approach toward managing its objects. While you still instantiate new objects somewhat like C++ and Java, Cocoa uses a reference-counting scheme to decide when the object can be safely discarded. With this scheme, the object uses an internal counter to keep track of the number of active references to it. When the count reaches zero, the object promptly self destructs.
Creation and Disposal
For the most part, Cocoa applications are written in either Objective-C or Objective-C++. Objective-C is a strict superset of ANSI C. Memory-management routines such as
free() are still available as part of stdlib.h, and you still use these routines to allocate and dispose of memory for your
union datatypes. However, you cannot use
free() to instantiate and dispose of Cocoa objects.
To instantiate Cocoa objects, you can use one of three approaches as provided by Objective-C.
The most common approach is to send to the object class an
[alloc] and an
[init] message, as in:
theObj = [[theClass alloc] init];
Here, you send
[alloc] message telling its
NSObject parent to allocate memory for the instance from the default memory zone (more on memory zones later). You then send it an
[init] message to initialize any objects or data structures it contains.
As a shorthand approach to instantiating Cocoa objects, you send a
[new] message to
theClass instead of the
theObj = [theClass new];
Sometimes, you send the
[init] messages like this:
theObj = [theClass alloc]; [theObj init];
This approach is useful when debugging Cocoa objects. If the object fails to instantiate, you can determine whether the problem occurs in the
init message phase of instantiation.
The second approach to instantiating Cocoa objects is using factory or convenience methods. These methods let you instantiate Cocoa objects, as well as initialize them to a specific value. Cocoa classes such as
NSString provide a range of convenience methods that let you do just that:
theStr = [NSString stringWithString:@"Dr. Dobbs"]; theNum = [NSNumber numberWithInt:42]; theURL = [NSURL URLWithString: @"http://www.ddj.com];
The third approach to instantiating Cocoa objects is to make a copy of an existing object. You do this by sending a
[copy] message to the latter:
theCopy = [theObj copy];
Each Cocoa class handles the
[copy] message differently. Immutable classes such as
NSNumber perform a shallow copy when they handle a
[copy] message. A shallow copy duplicates an object's pointers by reference. As a result, the copy has the same pointer references as the original. Mutable classes such as
NSMutableNumber perform deep copies. In deep copies, the object's pointers are duplicated by value. This process is repeated until all pointer references in the original are covered. Changing a pointer value in a deep-copy object will not affect the same pointer value in the original object.
There is a catch. Regardless of whether the Cocoa class is mutable or immutable, using the
[copy] message always creates an immutable copy. If you want to create a mutable copy of a mutable object, you have to send a
theCopy = [theObj mutableCopy];
Disposing of Objects
Once you are done using a Cocoa object, you can dispose of it by sending a
[release] message does not immediately deallocate the object. Instead, it decrements the internal reference count of that object by 1. Once that reference count reaches 0, the object self destructs by invoking its
dealloc method directly.
You can also dispose of the Cocoa object by sending it an
[autorelease] message defers the object's disposal by placing it in a specialized area called an "autorelease pool." Once placed, the object usually remains valid until the pool itself is discarded.
There is no convenient way of finding out whether the object is still valid once it receives an
[autorelease] message. Apple recommends you assume that autoreleased objects remain valid only within the scope of the current method. Apple also recommends not sending another
[release] or an
[autorelease] to an autoreleased object. Doing so generates either a
SIG_SEGV or an
Retention and Release
Again, Cocoa objects maintain an internal reference counter to decide when they should self-destruct. When objects are instantiated using either the
[init], [new], or
[copy] message, their reference count is initially set to 1. Sending a
[release] message to the same object decrements the reference count by 1. Once the count reaches zero, the object promptly self destructs by calling its
dealloc method. If you want to prevent the object from self destructing prematurely, you can retain the object by sending it a
[retain] message, as in Listing One. The
[retain] message increments the reference count by 1. Additional
[retain] messages will also increment the count by 1. To decrement the count, send a
[release] message to the object.
theObj = [theClass new]; \\ reference count is 1 [theObj retain]; \\ reference count is 1+1 = 2 [theObj retain]; \\ reference count is 2+1 = 3 [theObj release]; \\ reference count is 3-1 = 2 [theObj release]; \\ reference count is 2-1 = 1 [theObj release]; \\ reference count is 1-1 = 0 \\ theObj then self-destructs
To determine the current reference count, send a
[retainCount] message to the object; see Listing Two. The
[retainCount] message returns an unsigned integer indicating the number of active references to the object. However, it does not take into account any
[autorelease] messages that are still pending.
int theCount; theObj = [theClass new]; \\ reference count is 1 [theObj retain]; \\ reference count is 1+1 = 2 theNum = [theObj retainCount]; \\ returns the current count of 2 [theObj release]; \\ reference count is 2-1 = 1 theNum = [theObj retainCount]; \\ returns the current count of 1 [theObj release]; \\ reference count is 1-1 = 0