user3373665 user3373665 - 6 months ago 21
Objective-C Question

Explain underlying reasoning in this statement: "all objective-C objects must be referenced using pointers because they live on heap, not stack"

I don't really understand why objective-c objects always are referenced with pointers .

Consider this code:

// Create an array of Employee objects
NSMutableArray *employees = [[NSMutableArray alloc] init];

for (int i = 0; i < 10; i++) {
// Create an instance of Employee
Employee *person = [[Employee alloc] init];
// Put the employee in the employees array
[employees addObject:person];
}


Why not something like this?

// Create an array of Employee objects
NSMutableArray employees = [[NSMutableArray alloc] init];

for (int i = 0; i < 10; i++) {
// Create an instance of Employee
Employee person = [[Employee alloc] init];
// Put the employee in the employees array
[employees addObject:person];
}

Answer

Stack allocation is done by the compiler and a runtime environment. That means that there are many conventions and rules. Think about exceptions while constructing an object. Difficult to deal with them (and the same on deconstruction). The error mechanism of Cocoa while construction is very easy to understand and to implement. The construction mechanism itself is very easy to understand, to implement and highly flexible, because it is a part of the code, not of the runtime environment. If object creation happens "behind the scenes" it becomes more complex.

What is the disadvantage of "explicit" heap construction? Look to you code. You simply save an *, not more. No extra rules, no exceptions, no partial stack unrolling, … And with ARC the point in time to automatically delete the object is no deal anymore.

All problems in computer science can be solved by another level of indirection (David Wheeler)