2015年7月10日 UITableView 2

本文介绍UITableView中UITableViewCell的性能优化方法,包括使用缓存池减少cell重建次数,并通过static关键字减少内存消耗。

UITableView


UITableViewCell  的性能优化

原来的代码   这样的话 每当视图 中出现一条table 就会重新创建一个cell  会造成资源的浪费

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
//    indexPath.row     行
//    indexPath.section   组
     AutomobileGroups* a1 = self.automobileGroups[indexPath.section];
   
    UITableViewCell* cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
    cell.textLabel.text =  a1.automobiles[indexPath.row];
    return cell;
    
}


优化三部曲:

1.通过一个标示去缓存池中寻找可循环的cell

2.如果缓存池找不到可循环利用的cell:创建一个新的cell,给cell贴一个标示

3.给cell设置新的数据

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString* ID = @"car";
    
    //1.寻找缓存池中 是否有cell
    UITableViewCell* cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
    
    //2.如果没有的话 创建一个
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
    }
    
    //3.重置信息
    carGroup* cg = self.groups[indexPath.section];
    car* c = cg.cars[indexPath.row];
    cell.imageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"%@",c.icon]];
    cell.textLabel.text = [NSString stringWithFormat:@"%@",c.name];
    
    return  cell;
}

其中 static 也是很重要的优化 因为每次调用这个方法时都初始化一个id 也会消耗内存

如果有static 的话 只会在第一次 进行初始化


cell的 属性


显示 右边的索引

- (NSArray*)sectionIndexTitlesForTableView:(UITableView *)tableView{
    return [self.groups valueForKeyPath:@"title"];//kvc
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值