O'Reilly logo

Cocoa in a Nutshell by James Duncan Davidson, Michael Beam

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Deallocating Objects

When an object is ready to be destroyed (as determined by the reference counting mechanism), the system will give the object an opportunity to clean up after itself by calling the dealloc method defined by NSObject. If the object has created or retained any other objects’ reference by its instance variables, it must implement this method and perform the appropriate tasks to maintain integrity of the reference counting system.

In Example 1-8, the Song class retains the title instance variable in the setTitle: method. To properly implement memory management, you need to balance this retain with a release. Example 1-10 shows the release performed in the Song class’s dealloc method.

Example 1-10. Implementing a dealloc method
- (void)dealloc {
    [title release];
    [super dealloc];
}

This provides proper balance in the reference counting mechanism.

Warning

You should never call the dealloc method yourself. Always let the memory management methods do it.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required