开发者

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?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜