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];
}

最新文章

  1. MVC Autofac 注入点
  2. 多线程调用WebClient速度变慢的问题
  3. How to evaluate a transimpedance amplifier (part 1)
  4. HTTPConnection与HTTPClient的区别
  5. HW4.36
  6. 达内TTS6.0课件oop_day02
  7. iOS CGRectGetMaxY/CGRectGetMaxX
  8. 【Python】正则表达式re
  9. Python3学习笔记30-datetime模块
  10. 统一社会信用代码+组织机构代码 校验 python
  11. MySQL学习笔记1(增删查改)
  12. openssl rsa/pkey
  13. Java-简单的计算器(只能进行加法运算)
  14. variable 'QJsonArray array' has initializer but incomplete type
  15. C#用Linq查询Combox的数据源
  16. ping + 时间 日志
  17. ArcGIS 10 Raster Calculator 在哪儿
  18. 洛谷P3457 [POI2007]POW-The Flood [并查集,模拟]
  19. org.springframework.dao.DuplicateKeyException: a different object with the same identifier value was
  20. c++11 enable_shared_from_this

热门文章

  1. BL8810|USB2.0高速闪存读卡器芯片|BL8810规格书
  2. 使用 DML语句,对 “锦图网” 数据进行操作,聚合函数练习
  3. 【】Apache Ranger剖析:Hadoop生态圈的安全管家
  4. Linux-saltstack-4 jinjia模板得基本使用
  5. 解决zabbix server is running | No 的方法
  6. tomcat启动卡在了 At least one JAR was scanned for TLDs yet contained no TLDs 的根本原因与解决办法
  7. 新增访客数量MR统计之数据库准备
  8. vant引入及配置
  9. 【PTA】5-2 下列程序读入时间数值,将其加1秒后输出,时间格式为:hh: mm: ss,即“小时:分钟:秒”,当小时等于24小时,置为0。
  10. 《剑指offer》面试题25. 合并两个排序的链表