Search code examples
iosnsarrayretainautorelease

Can an autoreleased NSArray cause a memory leak?


I am trying to create an NSMutableArray using arrayWithArray, add two objects, sort, and store to an ivar as an NSArray. My code looks like this:

NSMutableArray *_mutableItems = [NSMutableArray arrayWithArray:[self.mainViewController.someDictionary allKeys]];

[_mutableItems addObject:@"Buildings"];
[_mutableItems addObject:@"Parking"];

self.curItems = [_mutableItems sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];

When I profile the app I get a memory leak for an NSArray after the view is popped. But what I don't understand is: aren't all of these objects autoreleased? Am I increasing the retain count when I assign it to the instance property?


Solution

  • Yes, setting the property is probably increasing the retain count. Specifically, _mutableItems will be autoreleased, but the array you create with sortedArrayUsingSelectoris retained by the property.

    Does your property declaration include retain or copy?

    @property (retain) NSArray *curItems;
    

    If so, in your class dealloc method, make sure you call release on the array;

    - (void)dealloc {
        [curItems release];
        [super dealloc];
    }