2012-02-20 36 views
0

我的程序向屏幕添加了不確定數量的視圖(由用戶在運行時確定),並通過將這些視圖存儲在數組中來跟蹤這些視圖。正確的方式釋放存儲在NSMutableArray中的視圖?

在我的視圖控制器

for (NSString *equationText in equationData) { 

// creates a FormulaLabel object for every object in the equationData mutable array 

FormulaLabel *tempLabel = [[FormulaLabel alloc] initWithFrame:CGRectMake(frame)]; 
[view addSubview:tempLabel]; 
[balanceItems addObject:tempLabel]; //balance items keeps track of all the views 

當我更新我的數據,我需要在屏幕上意見不同的安排,所以我想反映一個數據的變化將刪除所有意見的最快方法目前在屏幕上並從更新的數據添加新視圖。

對於這種方法,(據我所知)我需要從上海華刪除的意見,釋放他們,並刪除存儲在balanceItems的對象。然後我需要初始化新視圖,將它們添加到子視圖中,並將它們添加到數組中。但是,下面的代碼會生成一個錯誤。

for (UIView *view in balanceItems) { 

    [view removeFromSuperview]; 
    [view release]; 
} 

[balanceItems removeAllObjects]; 

什麼是正確的方式從超視圖以及數組中刪除視圖?

+0

你得到的錯誤是什麼?在哪一行? – sch 2012-02-20 19:58:55

+0

@sch'[balanceItems removeAllObjects]' – Mahir 2012-02-20 20:03:10

+0

它沒有給出具體的錯誤,它只是表示訪問不好 – Mahir 2012-02-20 20:03:44

回答

0

首先,你應該創建它們時正確釋放的觀點:

FormulaLabel *tempLabel = [[FormulaLabel alloc] initWithFrame:CGRectMake(frame)]; // retain count is 1 
[view addSubview:tempLabel]; // retain count is 2 
[balanceItems addObject:tempLabel]; // retain count is 3 
[tempLabel relase]; // retain count is 2 

您應該釋放tempLabel,因爲你有init方法獲得它,所以你擁有它。

然後,當您刪除視圖;你不必調用釋放:

for (UIView *view in balanceItems) { 
    [view removeFromSuperview]; // retain count is 1 
} 
[balanceItems removeAllObjects]; // retain count is 0 => view gets deallocated 

因爲視圖目前只保留了,但超級視圖和陣列,所以當你從他們刪除它,它就會被釋放。

+0

數組是否自己創建視圖副本? – Mahir 2012-02-20 20:20:54

+0

它不會創建新副本,它只是保留視圖。 – sch 2012-02-20 20:23:25