Objective-C Language Difference between allocation and initialization


In most object oriented languages, allocating memory for an object and initializing it is an atomic operation:

// Both allocates memory and calls the constructor
MyClass object = new MyClass();

In Objective-C, these are separate operations. The class methods alloc (and its historic sibling allocWithZone:) makes the Objective-C runtime reserve the required memory and clears it. Except for a few internal values, all properties and variables are set to 0/NO/nil.

The object then is already "valid" but we always want to call a method to actually set up the object, which we call an initializer. These serve the same purpose as constructors in other languages. By convention, these methods start with init. From a language point of view, they are just normal methods.

// Allocate memory and set all properties and variables to 0/NO/nil.
MyClass *object = [MyClass alloc];
// Initialize the object.
object = [object init];

// Shorthand:
object = [[MyClass alloc] init];