UITableView中的数据源和委托如何工作?

时间:2013-10-21 17:39:51

标签: ios objective-c uitableview

我是ios开发的新手。当我使用UITableView时,我实现了数据源和委托。喜欢以下两种方法:

 // Data source method
 - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

 // Delegate method
 - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 

但是,如果我理解正确,表视图不包含任何数据,并且它只存储足够的数据来绘制当前可见的行。因此,例如,如果我在表中有10个数据,并且当前只显示5个。这意味着委托方法运行5次,但在委托方法运行5次之前,数据源方法已经运行了10次以获得行数。我们使用数据源的原因是管理使用集合视图呈现的内容。所以我的问题是,数据源如何管理内容?数据源对象是否存储了所有这些表视图信息?(因为它在委托之前运行并且它知道表视图的总数)如果它存储表视图的信息,它似乎与委托冲突,因为表视图委托不保存任何数据, 对?

还有一个问题是我们在什么情况下只使用数据源?因为我们可以创建自定义委托吗?有没有我们只创建自定义数据源的情况?因为我已经看到数据源总是带有委托....谢谢!!!

2 个答案:

答案 0 :(得分:8)

UITableViewDataSource协议定义了UITableView用数据填充自身所需的方法。它定义了几个可选方法,但有两个是必需的(不是可选的):

// this method is the one that creates and configures the cell that will be 
// displayed at the specified indexPath
– tableView:cellForRowAtIndexPath: 

// this method tells the UITableView how many rows are present in the specified section
– tableView:numberOfRowsInSection:

此外,不需要以下方法,但也是一个好主意(也是数据源的一部分)

// this method tells the UITableView how many sections the table view will have. It's a good idea to implement this method even if you just return 1
– numberOfSectionsInTableView:

现在,方法–tableView:cellForRowAtIndexPath:将为UITableView中的每个可见单元格运行一次。例如,如果您的数据数组有10个元素但只有5个可见,–tableView:cellForRowAtIndexPath:将运行5次。当用户向上或向下滚动时,将再次为每个变为可见的单元调用该方法。

你说的是什么:“()数据源方法已经运行了10次以获得行数。”不是真的。数据源方法–tableView:numberOfRowsInSection:不会运行10次以获取行数。实际上这种方法只运行一次。此外,此方法在–tableView:cellForRowAtIndexPath:之前运行,因为表视图需要知道它必须显示多少行。

最后,方法–numberOfSectionsInTableView:也运行一次并且它在–tableView:numberOfRowsInSection:之前运行,因为表视图需要知道可能的部分。请注意,此方法不是必需的。如果您没有实现它,表格视图将假设只有一个部分。

现在我们可以将注意力集中在UITableViewDelegate协议上。该协议定义了与UITableView的实际交互有关的方法。例如,它定义了管理单元格选择的方法(例如,当用户点击单元格时),单元格编辑(插入,删除,编辑等),配置页眉和页脚(每个部分可以有页眉和页脚),等等 UITableViewDelegate中定义的所有方法都是可选的。实际上,您根本不需要实现UITableViewDelegate来获得表视图的正确基本行为,即显示单元格。

UITableViewDelegate的一些最常见的方法是:

// If you want to modify the height of your cells, this is the method to implement
– tableView:heightForRowAtIndexPath:

// In this method you specify what to do when a cell is selected (tapped)
– tableView:didSelectRowAtIndexPath:

// In this method you create and configure the view that will be used as header for
// a particular section
– tableView:viewForHeaderInSection:

希望这有帮助!

答案 1 :(得分:1)

datasource和delegate是Model-View-Controller范例的两个独立部分。除非您需要/想要,否则不需要连接代理。

委托方法根本不提供表的数据。数据源具有表的实际数据(存储在数组或字典或其他内容中)。

您似乎感到困惑,因为您将- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath列为委托方法,但它实际上是数据源协议的一部分。