UITableView的 reloadData 与reloadS
2022-08-22 本文已影响0人
一枝小王子的玫瑰花
UITableView的 reloadData 与reloadSections 、reloadRowsAtIndexPaths: 的区别
1. 复用规则不一样
- (void)reloadSections:(NSIndexSet *)sections withRowAnimation:(UITableViewRowAnimation)animation NS_AVAILABLE_IOS(3_0);
- (void)reloadRowsAtIndexPaths:(NSArray<NSIndexPath *> *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation API_AVAILABLE(ios(3.0));
- 当调用
[tableview reloadData]
的时候,当前展示的cell
是可以复用的。但是调用reloadSection
和reloadRowsAtIndexPaths:
时候,当前的cell
是不能复用的,会再创建一个或者多个出来,用来展示。创建出来以后,再执行reloadSection
和reloadRowsAtIndexPaths:
的时候cell
就能复用了
所以,使用
reloadSection
或reloadRowsAtIndexPaths:
时,需要注意,重新创建的cell
上的某些属性可能会发生改变,导致一些错误
例:CellA 如果此时是 firstResponder, 用后2者刷新时,会创建新的cellA' , 此时CellA 被新的 CellA'替换掉,firstResponder消失,会发生键盘消失的错误
2. 性能比较
- 简单列表,在数据源变化不大的情况下,reloadSection和reloadData两者在时间、CPU、内存相差并不大,甚至在某些情况,reloadData性能要优于reloadSection
思考:既然这样,为什么还要用 reloadSection呢?
例子考虑的是数据源不变的情况下cell的重绘制
但复杂场景,之所以考虑部分刷新reloadSections,是因为刷新每个section,cell不单单是cell的绘制,也都有包含I/O和运算操作
而这个时候 reloadData会触发其他不必要的运算和I/O
UITableview的主要作用是展示数据,而I/O操作其实不适合放在cell中。
更好的方法是:将获取数据源的代码放到次要线程中,这样主线程才能更好的加载视图。
我们常用的MVC,MVVM[架构]是为了将业务逻辑与视图尽量剥离,让UI更好的展示数据。