NSMutableArrayand started to wonder about the lifecycle of items in a collection. I know that the collections in the Foundation library
retainobjects when they're added and
releasethem when the collection
deallocs itself, so it makes sense that calling
removeObjectAtIndex:or any of the other "remove" methods would also
releasethe object in question.
removeObjectAtIndex:method doesn't return the removed object to you -- if you want to hold on to it, you need to call
objectAtIndex:first. It also makes sense that you need to
retainthe object you're holding on to. A quick inspection of my code showed that I wasn't doing that in at least one place, but my app wasn't crashing. This made me wonder if
objectAtIndex:was autoreleaseing the object it returned.
A quick Google search turned up an entry in William Woody's Development Chaos Theory blog entitled The lifespan of an object owned by NSMutableArray, or why Objective-C annoys me and Java makes me happy.
MyObject *obj = [myMutableArray objectAtIndex:0]; [[obj retain] autorelease]; // before removeObjectAtIndex [myMutableArray removeObjectAtIndex:0]; UseMyObject(obj);
You need to
retainthe item before you remove it from the
The moral of the story:
NSStringliterals are long lived and don't become invalid when a collection
releases them. If you build your NSMutableArray by doing something like this:
NSMutableArray *myMutableArray = [[NSMutableArray alloc] initWithObjects:@"one", @"two", @"three", nil];
You will mask a lot of memory management problems.