在同一索引路径中插入几行?



我想一次在我的UITableView中插入几行(带有一个动画(。

为此,我在self.tableView.performBatchUpdates中添加了插入代码:

tableView.performBatchUpdates({
    for object in objects {
        // my model holds all objects; inserting an object to 
        // the model returns the index path at the insertion position.
        let indexPath = model.insert(object)
        tableView.insertRows(at: [indexPath], with: .none)
    }
})

然后,我得到了一个'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (19) must be equal to the number of rows contained in that section before the update (10), plus or minus the number of rows inserted or deleted from that section (5 inserted, 0 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).'

我认为发生此错误是因为我两次指定了两个索引路径(19 - 2 * 2 = 15(。这有意义吗?同一个 IndexPath 在我的 indexPaths 数组中存在多次,因为我想在同一 indexPath 中添加几行(一个接一个(。
看来我做不到。

我的问题是我有另一个数组,其中包含我从数据库中获取的一些对象。每次收到一个新对象时,我都会先将其插入到我的数组中,将插入索引路径存储在变量中,然后,我想将对象添加到我的UITableView中。

我是否必须为每个对象更新表视图?

我的步骤:

  1. 从数据库接收对象
  2. 呼叫performBatchUpdates()
  3. performBatchUpdates()内:
    3.1 将对象插入数组并获取插入索引
    3.2 插入新行

我的想法会发生什么: 假设我在步骤 3.1 中取回索引 4。然后我插入新行。 另一个对象到达,我也找回索引 4。UITableView仅在performBatchUpdates()结束时重新加载,因此它会得到两次相同的对象。因此,它会引发错误,因为数据源函数表示必须有更多的行。

而不是

for indexPath in indexPaths {
    tableView.insertRows(at: [indexPath], with: .none)
}

你需要

tableView.insertRows(at: indexPaths , with: .none)

就像案例 1 中的第一个 insertRows 运行时一样,数据源正在更改为其他索引路径,这将导致此崩溃

首先,您必须跟踪最终的数组索引,该表视图将其用于其数据源委托,例如行数和cellForRowAt indexPath

该错误试图解释您的节具有的索引路径多于该节中的行数。 请记住,在尝试将所有对象插入到"表视图"部分之前,请将它们插入数组。

注意:查看您是要附加到数组还是插入淋浴以获得正确的索引号。

正如@T.Meyar所说 您正在调用 BatchUpdates,但仍尝试将单个索引路径添加到表视图。

tableView.performBatchUpdates({
   // removed for loop
   tableView.insertRows(at: indexPaths, with: .none)
})

我认为您必须为批处理更新添加回退,因为iOS 10不支持批处理更新,那么您必须像以前一样在for循环之间使用for循环

// Start update
tableView.beginUpdates
for indexPath in indexPaths {
    tableView.insertRows(at: [indexPath], with: .none)
}
// end updates
tableView.endUpdates

最新更新