tableViewCell的复用方法

一开始写tableView的时候我每一个Cell都加到了tableView的视图上去了,这样十分浪费内存。其实可以只创建若干个Cell,当其中的部分Cell滑出Device的界面时它就闲置了,当加载下一个cell时可以把这些闲置的cell复用,要注意的是复用时先前的cell的一些状态都是在的。
下面是我写的添加cell的代理方法,这种方法对内存消耗就很大了,因为没有

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [[UITableViewCell alloc] init];
    cell.textLabel.text = [self.arr[indexPath.section] objectAtIndex:indexPath.row];
    return cell;
}

所以要用缓存池来解决这个问题,先静态设置一个NSString 类型的identifier标志Cell,在缓存池中找有没空闲的cell如果有就直接把该Cell拿来重新赋值,否则创建一个cell。

static NSString  *identifier = @"myCell";

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if(cell == nil){
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    cell.textLabel.text = [self.arr[indexPath.section] objectAtIndex:indexPath.row];
    return cell;
}

如果是用nib文件自定义cell的话复用代码如下:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString  *identifier = @"myCell";
    PCDownLoadTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        NSArray *nibs = [[NSBundle mainBundle]loadNibNamed:@"PCDownLoadTableViewCell" owner:nil options:nil];
                cell = nibs.lastObject;
    }
    return cell;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值