Cell的重用原理
iOS设备的内存有限,如果用UITableView显示成千上万条数据,就需要成千上万个UITableViewCell对象的话,那将会耗尽iOS设备的内存。要解决该问题,需要重用UITableViewCell对象
重用原理:当滚动列表时,部分UITableViewCell会移出窗口,UITableView会将窗口外的UITableViewCell放入一个对象池中,等待重用。当UITableView要求dataSource返回UITableViewCell时,dataSource会先查看这个对象池,如果池中有未使用的UITableViewCell,dataSource会用新的数据配置这个UITableViewCell,然后返回给UITableView,重新显示到窗口中,从而避免创建新对象
还有一个非常重要的问题:有时候需要自定义UITableViewCell(用一个子类继承UITableViewCell),而且每一行用的不一定是同一种UITableViewCell,所以一个UITableView可能拥有不同类型的UITableViewCell,对象池中也会有很多不同类型的UITableViewCell,那么UITableView在重用UITableViewCell时可能会得到错误类型的UITableViewCell
解决方案:UITableViewCell有个NSString *reuseIdentifier属性,可以在初始化UITableViewCell的时候传入一个特定的字符串标识来设置reuseIdentifier(一般用UITableViewCell的类名)。当UITableView要求dataSource返回UITableViewCell时,先通过一个字符串标识到对象池中查找对应类型的UITableViewCell对象,如果有,就重用,如果没有,就传入这个字符串标识来初始化一个UITableViewCell对象
Cell的重用代码
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// 1.定义一个cell的标识
static NSString *ID = @”cell"; // 2.从缓存池中取出cell
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID]; // 3.如果缓存池中没有cell
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
}
最新文章
- MVC Autofac 注入点
- 多线程调用WebClient速度变慢的问题
- How to evaluate a transimpedance amplifier (part 1)
- HTTPConnection与HTTPClient的区别
- HW4.36
- 达内TTS6.0课件oop_day02
- iOS CGRectGetMaxY/CGRectGetMaxX
- 【Python】正则表达式re
- Python3学习笔记30-datetime模块
- 统一社会信用代码+组织机构代码 校验 python
- MySQL学习笔记1(增删查改)
- openssl rsa/pkey
- Java-简单的计算器(只能进行加法运算)
- variable 'QJsonArray array' has initializer but incomplete type
- C#用Linq查询Combox的数据源
- ping + 时间 日志
- ArcGIS 10 Raster Calculator 在哪儿
- 洛谷P3457 [POI2007]POW-The Flood [并查集,模拟]
- org.springframework.dao.DuplicateKeyException: a different object with the same identifier value was
- c++11 enable_shared_from_this
热门文章
- BL8810|USB2.0高速闪存读卡器芯片|BL8810规格书
- 使用 DML语句,对 “锦图网” 数据进行操作,聚合函数练习
- 【】Apache Ranger剖析:Hadoop生态圈的安全管家
- Linux-saltstack-4 jinjia模板得基本使用
- 解决zabbix server is running | No 的方法
- tomcat启动卡在了 At least one JAR was scanned for TLDs yet contained no TLDs 的根本原因与解决办法
- 新增访客数量MR统计之数据库准备
- vant引入及配置
- 【PTA】5-2 下列程序读入时间数值,将其加1秒后输出,时间格式为:hh: mm: ss,即“小时:分钟:秒”,当小时等于24小时,置为0。
- 《剑指offer》面试题25. 合并两个排序的链表