将新行插入 tableView 时是否必须调用 begin/endUpdates 方法?

Do I have to call begin/endUpdates method when a new row is inserted into the tableView?

  1. 描述:

    应用程序启动时会创建一个 table 视图,其中包含 3 行。如果点击导航栏中的添加按钮,将在 table 视图中添加一个新行。添加行操作背后的核心过程是方法 func insertRows(at:, with:).

    Apple documents and many stack-overflow answers (e.g., ) 建议将插入、删除或 select 视图的 table 行和部分的任何方法调用放在函数 beginUpdates() 和 [=13 之间=].

    我删除了 beginUpdates()endUpdates();事实证明,没有它们,应用程序也能正常工作。

  2. 问题:

    添加 beginUpdates()endUpdates() 有什么好处?

  3. 为什么问这个问题:

    函数 func insertRows(at:, with:) 调用委托函数 tableView(_:, cellForRowAt:) -> UITableViewCell 通过 dequeueReusableCell(withIdentifier:, for:) -> UITableViewCell 创建一个新单元格,这与 tableView 创建 3 个默认行的过程相同当应用程序启动时,但是那里没有这样的 beginUpdates / endUpdates 。那么,为什么我需要稍后在添加新行时添加此过程,而没有它们应用程序似乎仍在运行?

要为行和节的批量插入、删除和重新加载设置动画,请在连续调用 beginUpdatesendUpdates 定义的动画块中调用相应的方法。如果不在该块内调用插入、删除和重新加载方法,则行和节索引可能无效。可以嵌套调用 beginUpdatesendUpdates;所有索引都被视为只有外部更新块。

在一个块的结尾——也就是在 endUpdates returns 之后——table 视图像往常一样查询其数据源并委托行和部分数据。因此,支持 table 视图的集合对象应该更新以反映新的或删除的行或部分。

Apple Docs