UITableView的重用机制

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的重用

 

原文地址:https://www.cnblogs.com/hellocby/p/2514469.html