Creating constructors in Objective-C

12,781

Solution 1

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.

Solution 2

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];
}

Solution 3

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.

Share:
12,781
NSExplorer
Author by

NSExplorer

Updated on June 05, 2022

Comments

  • NSExplorer
    NSExplorer almost 2 years

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

    self = [super init];
    if ( self ) {
        //Initialization code here
    }
    
  • Chuck
    Chuck almost 13 years
    Actually, self in an init method is not a class. It's an uninitialized instance of the current class.