UITableview是大家常用的UIKit组件之一,使用中我们最常遇到的就是对delegate和dataSource这两个委托的使用。我们大多数人可能知道当reloadData这个方法被调用时,delegate和dataSource就会被回调,但是其中具体的细节,可能很多人不会去探究。
我最近有兴趣来探讨这个问题是因为我最近遇到过dataSource中有的方法被调用,但是有的方法没有被调用的情况,同时你会发现当tableview被add到一个superView的时候,也会触发了reloadData一样的回调。那么这两个委托究竟是怎么执行的呢?

  • 我们首先来看看苹果文档对reloadData的描述

    Call this method to reload all the data that is used to construct the table, 
    including cells, section headers and footers, index arrays, and so on. For 
    efficiency, the table view redisplays only those rows that are visible. It adjusts 
    offsets if the table shrinks as a result of the reload. The table view’s delegate or 
    data source calls this method when it wants the table view to completely reload 
    its data. It should not be called in the methods that insert or delete rows, 
    especially within an animation block implemented with calls to beginUpdates and 
    endUpdates.

    大致的意思就是说reload这个方法是用来构建table的,包括cell、section,而且只会对可见的行进行重新的绘制,当tableview想要完整的加载数据时,delegate和data source会调用此方法。增加删除行,尤其是需要block动画的时候不用用它。
    从这里只能看出个大概,并没有解释调用的原理。

  • 那么让我们先写一个最基本的tableview实现,然后对delegate和data source的回调设置一下断点看看。

iOS培训,Swift培训,苹果开发培训,移动开发培训

- (void)viewDidLoad {
    [super viewDidLoa
        
		

网友评论