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.

[sourcecode title=”// init and dealloc idioms” language=”objc”]
– (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.


The Objective-C Programming Language: Allocating and Initializing Objects

About idz

A professional software engineer dabbling in iOS app development.
This entry was posted in Objective-C and tagged , , , . Bookmark the permalink.

Leave a Reply