UITableView通過重用儲存格來達到節省記憶體的目的:通過為每個儲存格指定一個重用標識符(reuseIdentifier),即指定了儲存格的種類,以及當儲存格滾出螢幕時,允許恢複儲存格以便重用.對於不同種類的儲存格使用不同的ID,對於簡單的表格,一個標識符就夠了.
假如一個TableView中有10個儲存格,但是螢幕上最多能顯示4個,那麼實際上iPhone只是為其分配了4個儲存格的記憶體,沒有分配10個,當滾動儲存格時,螢幕內顯示的儲存格重複使用這4個記憶體,以下代碼用於測試記憶體的使用:
1 - (UITableViewCell *)tableView:(UITableView *)tableView 2 cellForRowAtIndexPath:(NSIndexPath *)indexPath 3 { 4 UITableViewCellStyle style = UITableViewCellStyleSubtitle; 5 static NSString *cellID = @"cell"; 6 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID]; 7 if (cell == nil) 8 { 9 cell = [[[UITableViewCell alloc] initWithStyle:style reuseIdentifier:@"cell"] autorelease];10 cell.detailTextLabel.text = [NSString stringWithFormat:@"Cell %d",++count]; //當分配記憶體時標記11 }12 cell.textLabel.text = [NSString stringWithFormat:@"Cell %d",[indexPath row] + 1]; //當新顯示一個Cell時標記13 return cell;14 }
通過運行此代碼 會發現實際上分配的Cell個數為螢幕最大顯示數, 當有新的Cell進入螢幕時,會隨機調用已經滾出螢幕的Cell所佔的記憶體,這就是Cell的重用
轉自:http://www.cnblogs.com/hellocby/archive/2012/05/23/2514469.html