Two staged creation in Cocoa and Objective C and why we need it

Autor: | Última modificación: 15 de noviembre de 2022 | Tiempo de Lectura: 1 minutos
Temas en este post:

Two Staged Creation of objects in Cocoa and Objective C

Unlike other OO languages such as Smalltalk or Java, Cocoa separates memory allocation from instance initialization. The very first versions of NextStep had single creation methods, as in Smalltalk.

This was changed, because of the need of several different allocation strategies to cup with the stringent memory limitations of that time. This is how allocWithZone: was born: to keep frequently used objects close to each other in memory.

Having several allocation methods and several instance initialization methods was causing a combinatorial explosion, so both responsibilities were decoupled.

Why we still need [[… alloc] init] in Objective C

Currently, there’s no need for zones and they are deprecated, however, there’s still a reason to keep the two-staged creation: Cocoa has no GC (at least for iOS) so the programmer MUST know when he allocates non-autoreleased memory!

This is the only reason for keeping the two-staged allocation strategy. Smalltalk and Java, having a GC have no need for this.