tableView性能优化 - cell 的循环利用

第一种:在数据源方法内部实现,首先从缓存池中获取,如果为空就自己创建

每当有一个 cell 进入视野范围内就会调用如下方法:

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    //重用标识,被 static 修饰的局部变量,只会初始化一次,在整个程序运行过程中,只有一份内存
    static NSString *cellID = @"yijiang";
    
    //先根据 cell 的标识去缓存池中查找可循环利用的 cell
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    
    //如果 cell 为 nil(缓存池中找不到对应的 cell)
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellID];
    }
    
    //覆盖数据
    cell.textLabel.text = @"数据";

    return cell;
}

第二种:通过注册来实现,首先从缓存池中获取 cell,如果缓存池中为空,就进行注册创建

  • 定义一个全局变量
//定义重用标识符
NSString *cellID = @"yijiang";
  • 注册某个标识对应的 cell 数据
- (void)viewDidLoad {
    [super viewDidLoad];
    
    //注册 cell
    [self.myTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:cellID];
}
  • 在数据源方法中返回 cell
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    //去缓存池中查找 cell
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];

    //覆盖数据融云 环信聊天室
    cell.textLabel.text = [NSString stringWithFormat:@"-------%zd------",indexPath.row];
    return cell;
}

第三种:通过 storyboard 来实现,首先根据 cell 的重用标识去缓存池中查找可循环利用的 cell,如果找不到 storyboard 就可以自动创建

cell1
cell2
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row % 2 == 0) {
        //根据 cell 的标识去缓存池中查找可循环利用的 cell
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell1"];
        return cell;
    }else{
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell2"];
        return cell;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容