Object Ownership, Retention, and Disposal

The problem of object ownership and disposal is a natural concern in object-oriented programming. When an object is created and passed around among various “consumer” objects in an application, which object is responsible for disposing of it? And when? If the object is not deallocated when it is no longer needed, memory leaks. If the object is deallocated too soon, problems may occur in other objects that assume its existence, and the application may crash.

The Foundation framework introduces a mechanism and a policy that helps to ensure that objects are deallocated when—and only when—they are no longer needed.

The policy is quite simple: you are responsible for disposing of all objects that you own. You own objects that you create, either by allocating or copying them. You also own (or share ownership in) objects that you retain. The flip side of this rule is that you should never release an object that you have not retained or created.

Object Initialization and Deallocation

In Cocoa you usually create an object by allocating it (alloc) and then initializing it (init or a variant). For example:

NSArray *myArray = [[NSArray alloc] init];

When an array’s init method is invoked, the method implementation initializes its instance variables to default values and completes other startup tasks. Similarly, when an object is deallocated, its dealloc method is invoked, giving it the opportunity to release objects it has created, free ...

Get Learning Cocoa now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.