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.
var lastObject: Any? The last object in the array. Returns the object located at the specified index. Returns the object at the specified index. Returns an array containing the objects in the array at the indexes specified by a given index set. Returns an enumerator object that lets you access each object in the array.
var array = NSArray (contentsOfURL: url!) Initializes a newly allocated array by placing in it the objects in the argument list. Recommended use is [NSArray arrayWithObjects:] instead of [ [NSArray alloc]initWithObjects:]
You may also choose to override, partially or fully, any other NSArray method for which you want to provide an alternative implementation. You might want to implement an initializer for your subclass that is suited to the backing store that the subclass is managing.
NSArray creates static arrays, and NSMutableArray creates dynamic arrays. You can use arrays when you need an ordered collection of objects. NSArray is “toll-free bridged” with its Core Foundation counterpart, CFArray. See Toll-Free Bridging for more information on toll-free bridging.
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];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With