Objective C - difference between init and constructor? Objective C - difference between init and constructor? objective-c objective-c

Objective C - difference between init and constructor?


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.