Creating constructors in Objective-C
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.
NSExplorer
Updated on June 05, 2022Comments
-
NSExplorer almost 2 years
Why do we always do this when creating constructors in Objective C?
self = [super init]; if ( self ) { //Initialization code here }
-
Brad Larson almost 13 yearsThe question Some beginner Objective-C/iPhone questions asks the same thing in its first part, and you should read Barry's answer there. See also Wil Shipley's "self = [stupid init];" article for more: wilshipley.com/blog/2005/07/self-stupid-init.html
-
NSExplorer almost 13 yearsJust found that this is best explained in Lecture 4 (at about 25 min) of Standford iOS Lecture.
-
-
Chuck almost 13 yearsActually,
self
in an init method is not a class. It's an uninitialized instance of the current class.