簡體   English   中英

iPhone內存泄漏和排序數組上的釋放問題

[英]iPhone memory leak and release problem on sorted array

我在以下代碼上遇到了一些麻煩:

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

如果使用此代碼,Instruments會說我內存泄漏,為什么?

使用此代碼:

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];

我也收到泄漏警告,但是,如果我自動釋放對象結果,則會發生內存錯誤。

我認為這是一個更好的答案。

- (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]; 
}

因此,您分配idDescriptor ,然后使用它,最后釋放它。 由於您要返回resultresult可以將它與return自動釋放。 我還有一個問題。 您是否在代碼的其他地方引用了result

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM