2010-03-19 69 views
0

我在我的代碼中使用以下方法:[CFArray release]:發送到解除分配的實例的消息

- (NSMutableArray *) newOrderedArray:(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]; 

    [idDescriptor release]; 

    NSMutableArray *result = [NSMutableArray arrayWithArray:orderArray]; 

    return result; 
} 

這是一種編碼良好的便捷方法嗎?我認爲,它返回一個自動釋放的NSMutableArray。

此方法由另一個調用:

- (id) otherMethod { 

    NSMutableArray *otherResult = [[[NSMutableArray alloc] initWithCapacity:[otherArray count]] autorelease]; 

    // I add some stuff to otherResult and then... 

    NSMutableArray *result = [dbUtils newOrderedArray:otherResult ByKey:@"objectId" ascending:NO]; 
    return result; 
} 

此方法(otherMethod)在某些視圖控制器中調用,我想在此處存儲返回的數組並在解除分配視圖控制器時釋放它。但是,當在這個視圖控制器中調用[result retain]時(因爲我需要它可用而且我不能允許它被釋放)我收到以下錯誤:

[CFArray release]: message sent to deallocated instance

我試過在調用retain之前記錄[result retainCount]並打印「1」。我不明白爲什麼在調用retain時會拋出錯誤。

謝謝,

A

回答

0

我在上面的代碼中看不到任何技術上的錯誤 - otherMethod應該返回一個自動發佈的NSMutableArray。你確定在調用retain時遇到錯誤?它看起來更像是你可能意外地在某個時候發佈了發佈而不是保留。

風格上,有一兩件事 - 在標題「新」方法應該總是返回 -autoreleased對象,所以你要麼別的命名方法的東西(如orderedArray...),或使用[[NSMutableArray alloc] initWithArray:]代替arrayWithArray。此外,方法簽名不應該大寫字母開頭的(所以ByKey應該byKey

+0

你是對的!問題不在於保留消息,它在賦值self.array = result因爲在以前的某個地方,我使用array = result(不使用self) – arielcamus 2010-03-19 17:15:08

0

試試這個:

NSMutableArray *otherResult = [[NSMutableArray initWithCapacity:[otherArray count]]; 

因爲initWithCapacity將返回一個autoreleased數組。現在你告訴Autoreleasepool釋放陣列兩次。

+0

'initWithCapacity:'不返回自動釋放對象。 – Wevah 2010-03-19 17:26:47

0

initWithCapacity:does not return an autoreleased object. – Wevah

AFAIK initWithCapacity是一個方便initializier,其按照約定歸還自動釋放的對象,所以如果對象只是一個本地方法中使用,autoreleasepool應該釋放它。精心設計?

+2

您正在考慮'arrayWithCapacity'。'initWithCa pacity'是一個初始值設定項,它只能用作[[[NSMutableArray alloc] initWithCapacity:]'的一部分,否則會發生崩潰(我認爲) - alloc返回一個非自動釋放對象,所以保留計數是1. – shosti 2010-03-19 19:13:34

+0

eman是正確的。你們兩個(「有希望有用」的知識,eman的確定性)應該讀取內存管理規則:http://developer.apple.com/mac/library/documentation/General/Conceptual/DevPedia-CocoaCore/MemoryManagement.html – 2010-03-19 23:37:55

相關問題