O'Reilly logo

Beginning Mac OS® X Programming by Drew McCormack, Michael Trent

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

7.9. Creating and Destroying Objects

An important part of any OO programming language is being able to create and destroy objects. In Objective-C, creation or instantiation of objects occurs in two stages: allocation and initialization. The NSObject method alloc takes care of allocating the memory needed to store the instance variables of an object. You should practically never need to override alloc to implement your own memory allocation scheme.

Initialization occurs in a method called an initializer. An initializer is a just a method like any other, and could be given any name; however, Cocoa convention says that it should begin with init. Initializers are responsible for allocating and initializing any instance variables, as well as ensuring that an initializer in the superclass is called. Here is an example of an initializer:

-(id)init {
    if ( self = [super init] ) {
        [self setCount:0];
        [self setGreeting:@"Hello"];
    }
    return self;
}

The if statement may seem a bit strange. It first assigns the self variable to the return value of the init method in the superclass. In Objective-C it is acceptable for an initializer to replace an object with a different instance and return that, so assigning self to the return value of super's init is good practice, even though self generally will not change.

In many OO languages, initializers, which are often called constructors, are special methods that are not inherited. In Objective-C, initializers are ordinary methods, which get inherited ...

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