简体   繁体   中英

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?

Yes, setting the property is probably increasing the retain count. Specifically, _mutableItems will be autoreleased, but the array you create with sortedArrayUsingSelector is 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];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM