Friday, July 08, 2011

Objective-C Memory Management Tip 1 - Remember to retain item(s) retrieved from an array

Very often in Objective-C, you have an array that contains a number of objects, like this:

NSMutableArray *array = [[NSMutableArray alloc] init];
[array addObject:@"Item 1"];
[array addObject:@"Item 2"];
[array addObject:@"Item 3"];

And often, you need to retrieve an object from the array and then assign it to another object, like this:
NSString *item = [array objectAtIndex:1];
However, the statement above is not safe as the object can be removed any time, like this:

NSString *item = [array objectAtIndex:1];
[array removeObjectAtIndex:1];

In this case, the item is no longer pointing to a valid memory location. You should instead use a retain on the object that is assigned to the object from the array:

NSString *item = [[array objectAtIndex:1] retain];
[array removeObjectAtIndex:1];
Doing so will ensure that even if the object in the array is removed, the object pointing to it will still remain valid.

In short, remember to retain item(s) retrieved from an array.

No comments: