Object creation

An object comes into runtime existence through a two-step process that allocates memory for the object and sets its state to reasonable initial values. To allocate an Objective-C object, send an alloc or allocWithZone: message to the object’s class. The runtime allocates memory for the object and returns a “raw” (uninitialized) instance of the class. It also sets a pointer (known as the isa pointer) to the object’s class, zeros out all instance variables to appropriately typed values, and sets the object’s retain count to 1.

After you allocate an object, you must initialize it. Initialization sets the instance variables of an object to reasonable initial values. It can also allocate and prepare other global resources needed by the object. You initialize an object by invoking an init method or some other method whose name begins with init. These initializer methods often have one or more parameters that enable you to specify beginning values of an object’s instance variables. If these methods succeed in initializing an object, they return it; otherwise, they return nil. If an object’s class does not implement an initializer, the Objective-C runtime invokes the initializer of the nearest ancestor instead.

image: Art/object_creation.jpg

The Form of an Object-Creation Expression

A convention in Cocoa programming is to nest the allocation call inside the initialization call.

MyCustomClass *myObject = [[MyCustomClass alloc] init];

When you create an object using this form, you should verify that the returned value is not nil before proceeding. In memory-managed code, an object’s instance variables and other allocated memory should be deallocated before that object itself is released.

Memory-Management Implications

In code that explicitly manages memory, the allocation and initialization procedure returns an object with a retain count of 1. This means that the client receiving the object now “owns” the object and is responsible for releasing it. You release it by sending it a release or autorelease message; the latter message causes a delayed release. If you do not release objects that you own, your program will leak memory.

Factory Methods

A factory method is a class method that, as a convenience to clients, creates an instance of a class. A factory method combines allocation and initialization in one step and returns an autoreleased instance of the class. Because the received object is autoreleased, the client must copy or retain the instance if it wants it to persist in memory. The names of factory methods have the following initial form:

+ (id)typeRemainderOfMethodName

where type is the class name minus the prefix and RemainderOfMethodName often begins with With or From. For example,

+ (id)dataWithContentsOfURL:(NSURL *)url;

Definitive Discussion

Prerequisite Articles

Did this document help you? Yes It's good, but... Not helpful...


Last updated: 2010-08-03