我有一个用于表 View 数据源的数组数组。在一个时间实例中,我可能不得不对此数据结构进行一些复杂的修改。 (例如,我可能需要执行的一系列操作是:在此处删除一行,在此处插入一行,在此处插入一个部分,删除另一行,插入另一行,删除另一行,插入另一部分-您得到了如果对于序列中的每个操作,我只是更新数据源,然后立即对表 View 进行相应的更新,则这样做很容易。换句话说,伪代码将如下所示:

[arrayOfArrays updateForOperation1];
[tableView updateForOperation1];

[arrayOfArrays updateForOperation2];
[tableView updateForOperation2];

[arrayOfArrays updateForOperation3];
[tableView updateForOperation3];

[arrayOfArrays updateForOperation4];
[tableView updateForOperation4];

// Etc.

但是,如果我将这些操作包含在beginUpdates/endUpdates“块”中,则此代码将不再起作用。要了解原因,首先从一个空的表格 View 开始成像,然后在第一部分的开头依次插入四行。这是伪代码:
[tableView beginUpdates];

[arrayOfArrays insertRowAtIndex:0];
[tableView insertRowAtIndexPath:[row 0, section 0]];

[arrayOfArrays insertRowAtIndex:0];
[tableView insertRowAtIndexPath:[row 0, section 0]];

[arrayOfArrays insertRowAtIndex:0];
[tableView insertRowAtIndexPath:[row 0, section 0]];

[arrayOfArrays insertRowAtIndex:0];
[tableView insertRowAtIndexPath:[row 0, section 0]];

[tableView endUpdates];

调用endUpdates时,表 View 发现您正在插入四行,所有行都碰撞到第0行!

如果我们确实要保留代码的beginUpdates/endUpdates部分,则必须做一些复杂的事情。 (1)我们将对数据源进行所有更新,而不会随之更新表 View 。 (2)我们找出所有更新之前的数据源部分如何映射到所有更新之后的数据源部分,以弄清楚我们需要对表 View 执行哪些更新。 (3)最后,更新表格 View 。伪代码看起来像这样,以完成我们在上一个示例中试图做的事情:
oldArrayOfArrays = [self recordStateOfArrayOfArrays];

// Step 1:
[arrayOfArrays insertRowAtIndex:0];
[arrayOfArrays insertRowAtIndex:0];
[arrayOfArrays insertRowAtIndex:0];
[arrayOfArrays insertRowAtIndex:0];

// Step 2:
// Comparing the old and new version of arrayOfArrays,
// we find we need to insert these index paths:
// @[[row 0, section 0],
//   [row 1, section 0],
//   [row 2, section 0],
//   [row 3, section 0]];
indexPathsToInsert = [self compareOldAndNewArrayOfArraysToGetIndexPathsToInsert];

// Step 3:

[tableView beginUpdates];

for (indexPath in indexPathsToInsert) {
    [tableView insertIndexPath:indexPath];
}

[tableView endUpdates];

为什么要为beginUpdates/endUpdates做所有这些事情?该文档说要使用 beginUpdates endUpdate 做两件事:
  • 同时对一组插入,删除和其他操作进行动画处理
  • “如果不在此块内进行插入,删除和选择调用,则表属性(例如行数)可能会变得无效。” (这到底意味着什么?)

  • 但是,如果我不使用beginUpdates/endUpdates,则表 View 看起来像是在同时对各种更改进行动画处理,并且我认为表 View 的内部一致性不会受到破坏。那么,使用beginUpdates/endUpdates执行复杂的方法有什么好处?

    最佳答案

    每次添加/删除表项时,都会调用tableView:numberOfRowsInSection:方法-除非您用begin/endUpdate包围这些调用。如果您的数组和表 View 项目不同步,如果没有开始/结束调用,将引发异常。

    关于ios - 与不这样做相比,为UITableView调用beginUpdates/endUpdates有什么好处?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23260279/

    10-12 00:15
    查看更多