alloc

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

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.

Acerca de Fernando Rodriguez

Fundador & Editor Jefe de justcodeit, Fernando Rodríguez (@frr149 & Linkedin) es desarrollador & un experto en la enseñanza de máxima calidad en programación y desarrollo para dispositivos iOS, Cocoa Touch, Objective C, Swift, Python, entre otros, aunque su mejor carta de presentación, es la opinión de sus alumnos: http://keepcoding.io/es/testimonio/ CLO en KeepCoding & Arunovo. Instructor de iOS Avanzado del Big Nerd Ranch. Profesor Asociado de la U-tad, autor invitado de revistas como iPhoneWorld, Applesfera.com & ponente habitual en conferencias dentro y fuera de España (iOSDevUK, CodeMotion, BCNDevCon, etc). En sus vidas anteriores fue un nerd de Python y Django, mago de Smalltalk, y para su pesar, galeote de C++ y un gran cocinero.

Share this:

Leave a comment