在UITableView中,如果对每一行数据都单独分配一个独立的cell,那么对于有成百上千个cell的tableview中肯定会占用大量内存。为了解决内存耗费的问题,UITableView通过重用cell来节省内存。

  以下是我个人对UITableViewCell重用机制的理解,如有不对的地方,希望大家能指出,帮助我不断修正:

  

  UITableView维护着两个队列,一个是当前可视的cell队列visiableCells,一个是可重用的cell队列reusableTableCells。

  假设我们共有100个cell提供展示,但是一屏最多只能提供10个cell进行展示。在最初,reusableTableCells为空,故

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];

  返回nil,所以会执行

    cell = [[UITableViewCell alloc] initWithFrame: CGRectZero reuseIdentifier: @"cell"];

  创建10个cell(cell0,cell1,......,cell9)存放在visiableCells队列中,占满整个屏幕,同时reusableTableCells仍为空,当cell下滑时,cell0离开屏幕,cell10进入屏幕,但是由于reusableTableCells为空,没有可以重用的cell,所以会继续创建一个新的cell,同时cell0会离开visiableCells而进入到reusableTableCells队列中。当再次下滑一个cell时,reusableTableCells中存在着cell0,所以会复用cell0而不是再次创建一个新的cell,于此同时,cell1离开屏幕,即离开visiableCells队列,进入到reusableTableCells。这便完成了UITableViewCell的重用。

  但是有一点比较奇怪,我在测试中发现好像reusableTableCells中事实上是存放了不只一个cell,并且每次是从其中随机选择一个cell进行复用。

 

  测试方法:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

    static NSInteger count = 0;

    static NSString *CellIdentifier = @"cell";

    UITableViewCell * cell = [tableviewdequeueReusableCellWithIdentifier:CellIdentifier];

    

    if (cell == nil) {

        cell = [[UITableViewCellalloc] initWithStyle:UITableViewCellStyleSubtitlereuseIdentifier:CellIdentifier];

        cell.detailTextLabel.text = [NSStringstringWithFormat:@"Cell %d", ++count];

    }

    cell.textLabel.text  = [NSStringstringWithFormat:@"cell %d", [indexPath row]];

    return  cell;

}

  结果显示是:

                   

  结果可以看出,一屏可以容纳10个cell,但是总的创建了12个cell,之后使用的cell都是复用的cell。

  复用的cell是从reusableTableCells中随机选择的一个cell的结果展示:

  

  这里说明在reusableTableCells有cell2和cell3可以复用时,它先使用的时cell3,再使用的是cell2,所以说明这不是按照顺序进行选择的。