2011-02-10 77 views
0

我很困惑是否使用UIView addTarget:action:導致該視圖被保留。具體來說,我有一個UITableView自定義單元視圖,這是在視圖控制器上註冊一個事件。這些單元格視圖是自動發佈的。自動釋放和選擇器

UITableViewCell *cell = [aTableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if (cell == nil) { 
     cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; 

UIView *cellView = [[UIView alloc] initWithFrame:viewRect]; 


[cellView addTarget:self action:@selector(dosSomething:) forControlEvents:UIControlEventTouchUpInside]; //is this not a good idea? 

[cellView autorelease]; //will this get released? 
} 

回答

1

addTarget:action:forControlEvent:不會以任何方式影響視圖的保留計數。您現在撥打autorelease的方式很好,您的視圖將被放置在autorelease池中並最終發佈。

請注意,爲了您的視圖有用,您必須將其作爲子視圖添加到某個其他視圖(例如您的單元格)。該觀點將保留在那裏,因爲它將取得你的觀點的所有權,但在這裏通過調用autorelease來正確處理事情。

+0

謝謝。我來自ActionScript世界,事件監聽器可以阻止虛擬機中的垃圾收集,我在這裏有點偏執。 – akaru 2011-02-10 09:05:44

0

你可以在這裏發佈cellView。釋放cellView並沒有問題,它不會導致任何崩潰。但請確保在函數稍後使用此視圖,並在釋放cellView之前將cellView添加到您單元格的內容視圖中。

UITableViewCell *cell = [aTableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if (cell == nil) { 
     cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; 

UIView *cellView = [[UIView alloc] initWithFrame:viewRect]; 


[cellView addTarget:self action:@selector(dosSomething:) forControlEvents:UIControlEventTouchUpInside]; //is this not a good idea? 

[cell.contentView addSubView:cellView]; 

[cellView release]; //will this get released? 
} 

這會很好地工作。