Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
}
like image 737
NSExplorer Avatar asked Jul 03 '11 19:07

NSExplorer


People also ask

Does Objective-C have constructors and destructors?

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.

How do you initialize an object in Objective-C?

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.

What is Instancetype in Objective-C?

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.

What is the purpose of a class constructor?

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.


2 Answers

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];
}
like image 132
The Bird Avatar answered Oct 02 '22 00:10

The Bird


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.

like image 27
Sherm Pendley Avatar answered Oct 02 '22 02:10

Sherm Pendley