简体   繁体   中英

iPhone memory leak and release problem on sorted array

I'm having some troubles with the code below:

NSSortDescriptor *idDescriptor = [[[NSSortDescriptor alloc] initWithKey:key ascending:ascending] autorelease];
NSArray *sortDescriptors = [NSArray arrayWithObject:idDescriptor];
NSArray *orderArray = [array sortedArrayUsingDescriptors:sortDescriptors];  
NSMutableArray *result = [NSMutableArray arrayWithArray:orderArray];

If I use this code, Instruments says I have a memory leak, why?

Using this code:

NSSortDescriptor *idDescriptor = [[[NSSortDescriptor alloc] initWithKey:key ascending:ascending] autorelease];
NSArray *sortDescriptors = [NSArray arrayWithObject:idDescriptor];
NSArray *orderArray = [array sortedArrayUsingDescriptors:sortDescriptors];

NSMutableArray *result = [[NSMutableArray alloc] initWithArray:orderArray];

I receive the leak warning too, however, if I autorelease the object result, a memory error happens.

Here is a better answer I think.

- (NSMutableArray *) orderArray:(NSMutableArray *)array ByKey:(NSString *)key ascending:(BOOL)ascending 
{ 
    NSSortDescriptor *idDescriptor = [[[NSSortDescriptor alloc] initWithKey:key ascending:ascending]];
    NSArray *sortDescriptors = [NSArray arrayWithObject:idDescriptor]; 
    NSArray *orderArray = [array sortedArrayUsingDescriptors:sortDescriptors]; 
    NSMutableArray *result = [[[NSMutableArray alloc] initWithArray:orderArray]];

    [release idDescriptor]; 
    return [result autorelease]; 
}

So, you allocate idDescriptor , then you use it, finally release it. Since you're returning result , you can autorelease it with the return. I have one more question though. Do you reference result elsewhere in your code?

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