Possible Duplicate:
Does lastObject in NSMutableArray return a copy of the object?
I’m following Stanford course on iOS development and I have a doubt.
The thing is that I have an array (operandStack) with “operands” (NSNumbers) and I want a function that pops out the last element and then erase it from the array. This is what the tutorial sais (and it works):
- (double)popOperand
{
NSNumber *operand = [self.operandStack lastObject];
if(operand) [self.operandStack removeLastObject];
return [operand doubleValue];
}
My question is: if with NSNumber *operand we’re just “pointing” to the last object and in the next line we remove this last object, how is it possible that we then return it? I mean, if we remove the last object and operand is just pointing to that object, then operand should be pointing to nothing, so I can’t understand how it’s possible that we can return operand…
I’d understand the code if operand was a copy of the last object of the array, but this is not the case…
Sorry for my english :S I hope I made myself clear.
Thanks,
Carlos
The
removeLastObjectmethod removes an object from the array, not from memory. Before you remove the object from the array, you assign it to a local variable. When compiling with ARC, local variables that point to objects have an implicit lifetime qualifier of__strong.Since you add the strong reference to the object before removing it from the array, your method temporarily takes ownership of it. Even if the method returned the object itself rather than its value, this would still work correctly, because ARC would insert an
autoreleasecall instead of areleaseat the end of the method.