Channels ▼
RSS

C/C++

Cocoa Memory Management

Source Code Accompanies This Article. Download It Now.


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 here—including MemLab, an application that lets you explore memory-management concepts—were 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 malloc() and free() are still available as part of stdlib.h, and you still use these routines to allocate and dispose of memory for your struct and union datatypes. However, you cannot use malloc() and 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 theClass an [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 [alloc] and [init] messages:

theObj = [theClass new];

Sometimes, you send the [alloc] and [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 alloc or 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 NSString and 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 NSMutableString and 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 [mutableCopy] message:

theCopy = [theObj mutableCopy];

Disposing of Objects

Once you are done using a Cocoa object, you can dispose of it by sending a [release] message:

[theObj release];

The [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:

[theObj autorelease];

The [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 EXC_BAD_ACCESS error.

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 [alloc] and [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.

Listing One

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.

Listing Two

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


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.
 

Video