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];
}
[/sourcecode]
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