tableViewCell的复用方法

来源:互联网 发布:java接口关键字 编辑:程序博客网 时间:2024/06/06 08:24

一开始写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";    if (nib == nil) {        nib = [UINib nibWithNibName:@"TableViewCell" bundle:nil];        [tableView registerNib:nib forCellReuseIdentifier:identifier];    }    TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];    cell.cellImage.image = [UIImage imageNamed:@"头像"];    cell.cellLabel.text = [arrBig[indexPath.section] objectAtIndex:indexPath.row];    return cell;}

PS:nib文件的复用nibsRegistered的写法也不是很稳妥,UINib这对会预加载进内存,然后创建的时候,会获取此对象并初始化。在内存充足的时候这个是没有问题的,但是当内存不足的时候,会释放掉此UINib,导致nibsRegistered = Yes,但是tableview注册的UINib已经被释放了,所以就会创建cell失败。

0 0
原创粉丝点击