The init and dealloc idioms.

For C++ programmers the first surprise waiting for them in Objective-C is that in a derived class they must explicitly call the init and dealloc methods of the superclass (roughly the equivalent of a constructor and destructor).

By following the idioms below you can avoid a lot of headaches.

- (id)init
{
    if(self = [super init])
    {
        // how to handle failure
        memberVariable = [[SomeOtherClass alloc] init];
        if(memberVariable == nil)
        {
            [self release];
            return nil;
        }
    }
    return self;
}

- (void)dealloc
{
    // Release anything you alloced or retained...
    [memberVariable release];
    // ... then dealloc your super class
    [super dealloc];
}

When accessing member variables in init and dealloc you show access them directly, not through accessors, to avoid side-effects.

Reference

The Objective-C Programming Language: Allocating and Initializing Objects

Posted in Objective-C | Tagged , , , | Leave a comment

iOS Developer Zone Goes Live

Welcome to iOS Developer Zone. I’m hoping that soon these pages will be filled with hints and tips for iPhone and iPad developers.

Posted in News | Leave a comment