开发者

iPhone memory leak and release problem on sorted array

开发者 https://www.devze.com 2022-12-21 13:37 出处:网络
I\'m having some troubles with the code below: NSSortDescriptor *idDescriptor = [[[NSSortDescriptor alloc] initWithKey:key ascending:ascending] autorelease];

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

精彩评论

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