Why do we always do this when creating constructors in Objective C?
self = [super init];
if ( self ) {
//Initialization code here
}
Traditionally in languages like Java and C# a constructor is where you would perform your initializations. In Objective-C you would do so in the init method even though you create a convenience constructor.
Out of the box in Objective-C you can initialize an instance of a class by calling alloc and init on it. // Creating an instance of Party Party *party = [[Party alloc] init]; Alloc allocates memory for the instance, and init gives it's instance variables it's initial values.
instancetype. Use the instancetype keyword as the return type of methods that return an instance of the class they are called on (or a subclass of that class). These methods include alloc , init , and class factory methods.
Purpose of Class Constructor Methods A constructor method is a special function that creates an instance of the class. Typically, constructor methods accept input arguments to assign the data stored in properties and return an initialized object.
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];
}
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With