2011-07-28 58 views
1

我一直拔出我的頭髮,試圖找出爲什麼這是泄漏。在我的.h文件中,我有一個非原子合成的屬性,保留了NSMutableArray。在我viewDidLoad中我把它聲明爲:泄漏NSMutableArray

self.tableData = [[NSMutableArray alloc] init]; 
[self.tableData removeAllObjects]; 
fillData(self.tableData); 

在我的申請,我稱之爲[self.tableData removeAllObjects],然後用fillData(self.tableData)函數重新填充它。此功能填補了從靜態的C++字符串組數據:

void fillData(NSMutableArray* list) 
{ 
    for (set<string>::const_iterator itr = sortedData.begin(); itr != sortedData.end(); ++itr){ 
     [list addObject:[NSString stringWithFormat:@"%s", ((string)*itr).c_str()]]; 
    } 
} 

在我的dealloc方法我做的:

[self.tableData removeAllObjects], [self.tableData release], tableData = nil; 

哪裏我誤事?儀器說它在[list addObject ....]行中。

感謝

+0

不是你的'((字符串)* itr).c_str()'調用返回一個不是自動釋放的字符串? –

+0

是的,但是被複制到應該自動釋放的NSString。所以我不確定這是如何造成泄漏的。我需要分配/自動釋放NSString嗎? – Alede

+0

看起來很好。如果將該行分成兩部分,將其分隔爲「const char * s =(* itr).c_str(); [list addObject:[NSString stringWithUTF8String:s];'? – Yuji

回答

4
self.tableData = [[NSMutableArray alloc] init]; 
[self.tableData removeAllObjects]; 
fillData(self.tableData); 

+1保留alloc,+1保留使用屬性的setter。您沒有從alloc平衡+1。如果你要使用的setter:

self.tableData = [NSMutableArray array]; 
fillData(self.tableData); 

注意​​中是完全沒有意義的。

這很奇怪,太:

[self.tableData removeAllObjects], [self.tableData release], tableData = nil; 

首先,不要打擾刪除的對象。當數組解除分配時,它將釋放所有對象。其次,使用setter調用release,然後立即做一個直接分配是不一致的。無論是做:

self.tableData = nil; 

或者:

[tableData release], tableData = nil; 

(注意,在使用的這一切的,的也純粹是爲了你的利益 - 它在生成的代碼沒有任何影響。)

此外,使用stringWithUTF8String:而不是stringWithFormat:

+0

你,先生,我感謝你。 – Alede

+0

+1,很好的解釋。 – InsertWittyName

0

不知道這是否是泄漏,但是這看起來是一個問題:

self.tableData = [[NSMutableArray alloc] init]; 

你說tableData是真實保留的屬性。請嘗試:

self.tableData = [NSMutableArray arrayWithCapacity:10]; 

這種方式屬性保留它,並且數組本身是autoreleased。您在dealloc中的發佈將使保留計數回到零。

+1

不要打擾'arrayWithCapacity:',除非你確切知道*總是*有多少項目。即使如此,它在很大程度上只是混亂的代碼,並沒有提供任何進口的實際優勢。 – bbum

0

問題是您的屬性設置爲保留,並將其設置爲已保留的對象。 你應該做的是這樣的:

// viewDidLoad 
NSMutableArray *array = [[NSMutableArray alloc] init]; 
self.tableData = array; 
[array release]; // this is important 

// dealloc 
self.tableData = nil; // will automatically release the array 
0

在你的dealloc,您使用的又保留了資料表的屬性。這是不是你真正想要的東西,所以做:

[tableData release]; 

[self->tableData release]; // not necessary, but some prefer it. 

self.tableData = nil; // property will handle release 

無需清除資料表,無需設置任何爲零(你正在釋放,所以什麼都不會訪問它)。