Reputation: 12149
Why do we always do this when creating constructors in Objective C?
self = [super init];
if ( self ) {
//Initialization code here
}
Upvotes: 5
Views: 13125
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
Reputation: 823
Read this apple document on initialization http://developer.apple.com/library/mac/#documentation/cocoa/Conceptual/ObjectiveC/Chapters/ocAllocInit.html
Upvotes: 0
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
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