Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective C - difference between init and constructor?

I'm trying to find the difference between init and constructor in Objective C.I'm not a C developer, but I need to convert some Objective C-code to Java and actually I can't understand the difference between both things.

like image 618
Android-Droid Avatar asked Aug 29 '11 11:08

Android-Droid


People also ask

What is the difference between INIT and constructor?

Initializer blocks effectively become part of the primary constructor. The constructor is the secondary constructor. Delegation to the primary constructor happens as the first statement of a secondary constructor, so the code in all initializer blocks is executed before the secondary constructor body.

What is the difference between object and constructor?

A constructor is a function that creates and initializes an object. JavaScript provides a special constructor function called Object() to build the object. The return value of the Object() constructor is assigned to a variable. The variable contains a reference to the new object.

What is init 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.

Which will called first constructor or init?

The constructor is called first or else there would be no object to call init() on. And yes, the init() method is indeed called by the container.


1 Answers

In Objective-C, the way an object comes to life is split into two parts: allocation and initialization.

You first allocate memory for your object, which gets filled with zeros (except for some Objective-C internal stuff about which you don't need to care):

myUninitializedObjectPointer = [MyClass alloc];

The next stage is initialization. This is done through a method that starts with init by convention. You should stick to this convention for various reasons (especially when using ARC), but from a language point of view there's no need to.

myObjectPointer = [myUnitializedObjectPointer init];

or in one line:

myObjectPointer = [[MyClass alloc] init];

In other languages these init methods are called constructors, but in Objective-C it is not enforced that the "constructor" is called when the object is allocated. It's your duty to call the appropriate init method. In languages like C++, C# and Java the allocation and initialization are so tightly coupled that you cannot allocate an object without also initializing it.

So in short: the init methods can be considered to be constructors, but only by naming convention and not language enforcement. To Objective-C, they're just normal methods.

like image 107
DarkDust Avatar answered Oct 01 '22 07:10

DarkDust