NSExplorer
NSExplorer

Reputation: 12149

Creating constructors in Objective-C

Why do we always do this when creating constructors in Objective C?

self = [super init];
if ( self ) {
    //Initialization code here
}

Upvotes: 5

Views: 13125

Answers (4)

The Bird
The Bird

Reputation: 407

you can create constructor and destructor in objective-c with

-(id) init
{
    self = [super init];
    if(self)
    {
       //do something
    }
    return self;
}
-(void) dealloc
{
   [super dealloc];
}

Upvotes: 11

Wolfgang Schreurs
Wolfgang Schreurs

Reputation: 11834

self is a class based on some superclass (e.g. UIViewController, NSObject - see your interface file to be sure which one). The superclass might need some form of initialization in order for the subclass to work as expected. So by first initializing the superclass we make sure default properties and the like are set. Without initializing the superclass first, we might experience some very unexpected behavior, especially in more complex objects like ViewControllers and the like.

Upvotes: 1

Sherm Pendley
Sherm Pendley

Reputation: 13622

We reassign to self because [super init] is allowed to return a different object than the one it was called on. We if (self) because [super init] is allowed to return nil.

Upvotes: 8

Related Questions