代码之家  ›  专栏  ›  技术社区  ›  Mark

UITableView dequeueReusableCellWithIdentifier理论

  •  33
  • Mark  · 技术社区  · 15 年前

    UITableView

    新的,可以极大地提高表视图的性能。”

    来源:iOS参考库

    要重用所使用的单元格,请执行以下操作:

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    

    现在,我想知道的是,这里到底发生了什么?它是否在TableView中查看是否有一个具有该标识符的单元格,并只返回该标识符?嗯,是的,但是如果它发送一个引用而不是分配,并且我有一个表视图,假设有4个具有相同标识符的单元格都是可见的。它如何在不分配内存的情况下将自身乘以四个实例?

    prepareForReuse 方法,并将其自身从队列中移除。

    3 回复  |  直到 12 年前
        1
  •  44
  •   Duck    12 年前

    dequeueReusableCellWithIdentifier: 只返回一个 cell 如果已标记为可重复使用。这就是为什么在几乎所有 cellForRowAtIndexPath:

    
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (nil == cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                       reuseIdentifier:CellIdentifier];
    }
    
    // Do something to cell
    
    return cell;
    
    

    实际上,将分配足够的行来填充 tableview cells scroll 在屏幕外,它们将从 table 并标记为已准备就绪 reuse . 随着“可用单元格”队列的增长,您请求 dequeued cell 将开始获取 使用,此时您将不再需要分配。

        2
  •  13
  •   Stefan Arentz    15 年前

    的代码 deqeueueReusableCellsWithIdentifier: 会像这样:

    (摘自我自己的一个项目,在这个项目中,我对页面滚动视图中的视图/页面进行了类似的操作)

    - (UIView*) dequeueReusablePage
    {
        UIView* page = [reusablePages_ anyObject];
        if (page != nil) {
            [[page retain] autorelease];
            [reusablePages_ removeObject: page];
        }
        return page;
    }
    

    所以它保持了一个简单的 NSMutableSet 使用可重用对象。

    所以你从一个空的集合开始,只有当你有更多的数据要显示,然后在屏幕上可见时,集合才会增长。

    用过的单元格从屏幕顶部滚动,放入集合中,然后取屏幕底部显示的单元格。

        3
  •  2
  •   Ram Madhavan    9 年前

    目的 dequeueReusableCellWithIdentifier 就是用更少的内存。如果我们在一个表视图中使用100个单元格,那么需要每一个表视图创建100个单元格是时候了。是时候了减少应用程序功能并可能导致崩溃。 为了这个 dequeueReusableCellWithIdentifier可重用单元 初始化我们创建的特定数量的单元格,这些单元格将再次用于进一步处理。

    -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        static NSString *TableIdentifier = @"YourCellIdentifier";
    
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:TableIdentifier];
    
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:TableIdentifier];
        }
    
        ExternalClassTableViewCell *myCell = [[ExternalClassTableViewCell alloc]init];
        myCell.MyCellText.text = [tableData objectAtIndex:indexPath.row];
        myCell.MyCellImage.backgroundColor = [UIColor blueColor];
    
        return cell;
    }