Returning a local variable


#1

I see a LOT of this code in Objective-C examples, not just in the BNR book.

-(SomeObject*)someFunction { SomeObject *object = [[SomeObject alloc] init]; // Do something return object; }

Doesn’t object go out of scope in this case? What am I missing Objective-C?


#2

The variable named object goes out of scope, not the object proper it is pointing to.
The pointer (memory address of the object proper) in the variable is copied out to the caller when the function returns.


#3

I realize now that alloc gets memory off the heap, akin to C’s malloc()) and C++'s new().