I'm working on an iPhone project where I would like to retrieve an object from an NSMutableArray, remove the object from the array and then use it later. The code looks something like this:
NSMutableArray * array;
// fill the array
NSObject * obj = [array lastObject];
[array removeLastObject];
// do something with obj (in the same function)
array is the only entity with a retain on the object that is being accessed. Is this safe to do? I would assume that this would only work if lastObject autoreleased the object which is something that I can't figure out if it does.
解决方案
Why not call
[array removeLastObject]
at the end of your function? That's one fewer release/retain. It might make your code more readable/less cluttered.
For the record the Apple documentation:
Like NSArray, instances of
NSMutableArray maintain strong
references to their contents. If you
do not use garbage collection, when
you add an object to an array, the
object receives a retain message. When
an object is removed from a mutable
array, it receives a release message.
If there are no further references to
the object, this means that the object
is deallocated. If your program keeps
a reference to such an object, the
reference will become invalid unless
you send the object a retain message
before it’s removed from the array.
For example, if anObject is not
retained before it is removed from the
array, the third statement below could
result in a runtime error:
id anObject = [[anArray objectAtIndex:0] retain];
[anArray removeObjectAtIndex:0];
[anObject someMessage];