iOS边练边学--UITableView性能优化之三种方式循环利用

一、cell的循环利用方式1:

 1 /**
 2  *  什么时候调用:每当有一个cell进入视野范围内就会调用
 3  */
 4 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
 5 {
 6     // 0.重用标识
 7     // 被static修饰的局部变量:只会初始化一次,在整个程序运行过程中,只有一份内存
 8     static NSString *ID = @"cell";
 9 
10     // 1.先根据cell的标识去缓存池中查找可循环利用的cell
11     UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
12 
13     // 2.如果cell为nil(缓存池找不到对应的cell)
14     if (cell == nil) {
15         cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
16     }
17 
18     // 3.覆盖数据
19     cell.textLabel.text = [NSString stringWithFormat:@"testdata - %zd", indexPath.row];
20 
21     return cell;
22 }

二、cell的循环利用方式2:--此方法的弊端是只能使用系统默认的样式

<1>定义一个全局变量

 1 // 定义重用标识 2 NSString *ID = @"cell"; 

<2>注册某个标识对应的cell类型

1 // 在这个方法中注册cell
2 - (void)viewDidLoad {
3     [super viewDidLoad];
4 
5     // 注册某个标识对应的cell类型
6     [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:ID];
7 }

<3>在数据源方法中返回cell

 1 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
 2 {
 3     // 1.去缓存池中查找cell
 4     UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
 5 
 6     // 2.覆盖数据
 7     cell.textLabel.text = [NSString stringWithFormat:@"testdata - %zd", indexPath.row];
 8 
 9     return cell;
10 }

三、cell的循环利用方式3:

<1>在storyboard中设置UITableView的Dynamic Prototypes Cell

<2>设置cell的重用标识

<3>在代码中利用重用标识获取cell

 1 // 0.重用标识
 2 // 被static修饰的局部变量:只会初始化一次,在整个程序运行过程中,只有一份内存
 3 static NSString *ID = @"cell";
 4 
 5 // 1.先根据cell的标识去缓存池中查找可循环利用的cell
 6 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
 7 
 8 // 2.覆盖数据
 9 cell.textLabel.text = [NSString stringWithFormat:@"cell - %zd", indexPath.row];
10 
11 return cell;
原文地址:https://www.cnblogs.com/gchlcc/p/5279479.html