(1) iOS设备的内存有限,如果用UITableView显示成千上万条数据,就需要成千上万 个UITableViewCell对象的话,那将会耗尽iOS设备的内存。要解决该问题,需要重用UITableViewCell对象
(2)重⽤原理:当滚动列表时,部分UITableViewCell会移出窗口,UITableView会将窗口外的UITableViewCell放入一个缓存池中,等待重用。当UITableView要求dataSource返回 UITableViewCell时,dataSource会先查看这个缓存池,如果池中有未使用的 UITableViewCell,dataSource则会用新的数据来配置这个UITableViewCell,然后返回给 UITableView,重新显示到窗口中,从而避免创建新对象 。这样可以让创建的cell的数量维持在很低的水平,如果一个窗口中只能显示5个cell,那么cell重用之后,只需要创建6个cell就够了。
(3)注意点:还有⼀个非常重要的问题:有时候需要自定义UITableViewCell(用⼀个子类继 承UITableViewCell),而且每⼀行⽤的不一定是同一种UITableViewCell,所以一 个UITableView可能拥有不同类型的UITableViewCell,缓存池中也会有很多不同类型的 UITableViewCell,那么UITableView在重⽤用UITableViewCell时可能会得到错误类型的 UITableViewCell
解决⽅方案:UITableViewCell有个NSString *reuseIdentifier属性,可以在初始化UITableViewCell的时候传入一个特定的字符串标识来设置reuseIdentifier(一般用UITableViewCell的类名)。当UITableView要求dataSource返回UITableViewCell时,先 通过一个字符串标识到缓存池中查找对应类型的UITableViewCell对象,如果有,就重用,如果没有,就传入这个字符串标识来初始化⼀一个UITableViewCell对象。
说明:一个窗口放得下(可视)三个cell,整个程序只需要创建4个该类型的cell即可。
二.传统方式
// 定义一个重用标识
static NSString *ID = @"wine";
// 1.去缓存池中取是否有可循环利用的cell
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
// 2.如果缓存池没有可循环利用的cell,自己创建
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
// NSLog(@"cellForRowAtIndexPath--%zd",indexPath.row);
}
// 3.设置数据
cell.textLabel.text = [NSString stringWithFormat:@"第%ld行数据",indexPath.row];
三.注册的方式
// ViewController.m
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
NSString *ID = @"wine";
- (void)viewDidLoad {
[super viewDidLoad];
// 设置tableView 每一行cell的高度
self.tableView.rowHeight = 100;
// 根据ID 这个标识 注册对应的cell类型 为UITableViewCell(只注册一次)
[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:ID];
}
#pragma mark - 数据源方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 200;
}
/**
* 每当一个cell进入视野范围内就会调用1次
*/
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// 1.去缓存池中取是否有可循环利用的cell
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
// 2.设置数据
cell.textLabel.text = [NSString stringWithFormat:@"第%ld行数据",indexPath.row];
return cell;
}
缓存优化的思路:
(1)先去缓存池中查找是否有满足条件的cell,若有那就直接拿来
(2)若没有,就自己创建一个cell
(3)创建cell,并且设置一个唯一的标记(把属于“”的给盖个章)
(4)给cell设置数据
注意点:
定义变量用来保存重用标记的值,这里不推荐使用宏(#define来处理),因为该变量只在这个作用域的内部使用,且如果使用宏定义的话,定义和使用位置太分散,不利于阅读程序。由于其值不变,没有必要每次都开辟一次,所以用static定义为一个静态变量。