概述
当tableView 中的cell有很多时,可能会造成内存不够的情况。iOS中有cell缓存池,每个cell有个标志,不同是为了区别不同cell。
当一个屏幕只能显示4个cell时,只需要创建多一个cell在缓存池中,就可以满足满足上下滑时,cell的循环使用。
重用原理
重用原理:当滚动列表时,部分UITableViewCell会移出窗口,UITableView会将窗口外的UITableViewCell放入一个对象池中,等待重用。当UITableView要求dataSource返回UITableViewCell时,dataSource会先查看这个对象池,如果池中有未使用的UITableViewCell,dataSource会用新的数据配置这个UITableViewCell,然后返回给UITableView,重新显示到窗口中,从而避免创建新对象。
循环使用实现
/**
* 每当有一个cell进入视野范围内,就会调用
*/
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//定义cell的标志。static修饰局部变量:可以保证局部变量只分配一次存储空间(只初始化一次)
static NSString *ID = @"hero";
//1.通过一个标志去缓存池中寻找可以循环利用的cell
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
//2.如果没有可以循环利用的cell,从缓存池中取出cell
if (cell == nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
}
//3.给cell设置新的数据
QTHero *hero = self.heros[indexPath.row];
//4.设置cell的属性
cell.textLabel.text = hero.name;
cell.detailTextLabel.text = hero.intro;
cell.imageView.image = [UIImage imageNamed:hero.icon];
return cell;
}