2012-05-04 26 views
1

如果我們給所有單元使用相同的標識符,則消失單元使用出現單元的內存。當我滾動表視圖時,意味着內容會重複。但是,如果我們給出差異標識符,那麼每個單元格都將擁有自己的內存位置並完美地顯示數據。UItableviewcell「單元標識符」內存管理

現在假設我有1000或更多的記錄要在表視圖中加載。如果我將給出不同的標識符,內存中將會有大量的分配。那麼是否有任何解決方案能夠以最少的內存分配完美地顯示數據

這是我如何定義小區標識:

-(UITableViewCell *)tableView:(UITableView *)tableView 
     cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    NSString *cellIdentifier = [NSString stringWithFormat:@"%d%d",indexPath.section,indexPath.row]; 
    UITableViewCell *Cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier]; 

    if (Cell == nil) 
    { 
     Cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle 
             reuseIdentifier:cellIdentifier]; 
    } 
} 
+4

爲什麼你不想重用表格單元有什麼特別的原因嗎? – Ilanchezhian

+0

重用將顯示當前單元格使用其內存的消失單元的內容... – NSPratik

+1

但是,在重新使用單元出列後,可以使用要顯示的正確內容重新配置它。不重複使用單元格的問題是,如果用戶Table View足夠長並且用戶快速滾動它,將導致大量的alloc/deallocs,這將導致不平滑的滾動。 – flainez

回答

1

你應該清除出列單元格的內容,如清空標籤和其他內容。如果您爲每個單元分配單獨的內存,您將很容易出現內存不足的情況。完美的內存管理仍在重用單元。

2

您遇到不恰當地使用小區標識由你造成的問題。對於要重用的所有單元,單元標識符應該相同。看看這個模板,它應該解釋正確的方法:

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    NSString *cellIdentifier = @"MY_CELL"; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier]; 
    if (cell == nil) { 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier]; 
     // everything that is similar in all cells should be defined here 
     // like background colors, label colors, indentation etc. 
    } 
    // everything that is row specific should go here 
    // like label text, progress view progress etc. 
    return cell; 
} 

Btw。使用駱駝案例來命名你的變量,大寫的名字是爲類名命名的。

+2

我認爲值得注意的是,這段代碼僅適用於使用ARC的項目。否則,你會泄漏細胞。不使用ARC的項目的解決方案是在返回單元之前自動釋放單元。 – flainez

+1

好點,我傾向於忘記,不是每個人都能夠使用ARC很幸運。 – lawicko