UITableView的性能优化
来源:互联网 发布:韩顺平mysql优化 编辑:程序博客网 时间:2024/04/27 09:36
iOS设备的内存有限,如果用UITableView显示成千上万条数据,就需要成千上万个UITableViewCell对象的话,那将会耗尽iOS设备的内存。要解决该问题,需要重用UITableViewCell对象。
注:如果不使用缓存池的情况,离开屏幕的cell也会自动被销毁,但是在拖动的过程中cell会不断的创建和销毁。
性能优化概述
重用原理
当滚动列表时,部分UITableViewCell会移出窗口,UITableView会将窗口外的UITableViewCell放入一个对象池中,等待重用。当UITableView要求dataSource返回UITableViewCell时,dataSource会先查看这个对象池,如果池中有未使用的UITableViewCell,dataSource会用新的数据配置这个UITableViewCell,然后返回给UITableView,重新显示到窗口中,从而避免创建新对象。
对每个存放在缓存池中的cell设置一个标识
问题:
有时候需要自定义UITableViewCell(用一个子类继承UITableViewCell),而且每一行用的不一定是同一种UITableViewCell,所以一个UITableView可能拥有不同类型的UITableViewCell,对象池中也会有很多不同类型的UITableViewCell,那么UITableView在重用UITableViewCell时可能会得到错误类型的UITableViewCell
解决方案:
UITableViewCell有个NSString *reuseIdentifier属性,可以在初始化UITableViewCell的时候传入一个特定的字符串标识来设置reuseIdentifier(一般用UITableViewCell的类名)。当UITableView要求dataSource返回UITableViewCell时,先通过一个字符串标识到对象池中查找对应类型的UITableViewCell对象,如果有,就重用,如果没有,就传入这个字符串标识来初始化一个UITableViewCell对象
步骤和代码
1.定义一个cell的标识
2.从缓存池中取出cell
3.如果缓存池中没有cell
4.设置cell的属性…
/** * 每当有一个cell进入视野范围内,就会调用 */-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ // static修饰局部变量:可以保证局部变量只分配一次存储空间(只初始化一次) // 1. 定义一个cell的标识 static NSString *ID = @"hero"; // 2. 从缓存池中取出cell // dequeue出列(查找) UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID]; // 3. 如果缓存池中没有cell,则创建一个cell if(cell == nil){ cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID]; } // 4. 设置cell的属性 MJHero *hero = self.heros[indexPath.row]; cell.textLabel.text = hero.icon; cell.detailTextLabel.text = hero.intro; cell.imageView.image = [UIImage imageNamed:hero.icon]; return cell;}
- 优化UITableView的性能
- UITableView的性能优化
- UITableView的性能优化
- UITableView的性能优化
- UITableView的性能优化
- UItableView的性能优化
- UITableView的性能优化
- UITableView的性能优化
- UITableView的性能优化
- UITableView的性能优化
- UITableView的性能优化
- UITableView的性能优化问题
- 关于UITableView的性能优化
- 如何优化UITableView的性能
- 如何优化UITableView的性能
- UITableView的性能优化整理
- iOS 优化UITableView的性能
- 关于UITableView的性能优化
- Android布局fill_parent、wrap_content和match_parent的区别
- Redis事务介绍
- 收不到组播的异常情况
- Git 使用心得
- 你需要知道的12个Git高级命令
- UITableView的性能优化
- docker下gitlab运行
- Shell if else语句
- HDU(3874)树状数组+离线
- matlab中fix, floor, ceil, round 函数的使用方法
- java 导出excel设置数字格式
- Shell case esac语句
- 【选择图片Jar】“MVC“来实现逻辑处理与View视图的分离(五)
- 基于C/S模式的信息学院电子考试系统