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 warni开发者_Go百科ng 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?
精彩评论