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.
我也收到泄漏警告,但是,如果我自动释放对象结果,则会发生内存错误。
1 个解决方案
#1
2
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?
所以,你分配idDescriptor,然后你使用它,最后释放它。由于您返回结果,您可以使用返回自动发布。我还有一个问题。你在代码的其他地方引用了结果吗?
#1
2
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?
所以,你分配idDescriptor,然后你使用它,最后释放它。由于您返回结果,您可以使用返回自动发布。我还有一个问题。你在代码的其他地方引用了结果吗?