在同一IndexPath插入几行?

时间:2018-08-07 14:04:03

标签: ios swift uitableview uikit

我想一次插入多个行(带有一个动画)到我的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).'

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

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

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

我的步骤:

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

我认为会发生什么: 假设我在步骤3.1取回索引4。然后我插入新行。 另一个对象到达了,我也得到了索引4。UITableView仅在performBatchUpdates()的末尾重新加载,因此它将两次获得相同的对象。因此,它会引发错误,因为数据源函数说必须有更多的行。

2 个答案:

答案 0 :(得分:0)

代替

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

您需要

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

与案例1中的第一个insertRows运行时一样,正在更改其他indexPath的数据源,这将导致此崩溃

答案 1 :(得分:0)

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

该错误试图说明您的节中的indexPaths比该节中的行数多。在尝试将所有对象插入到TableViews部分之前,请记住将所有对象插入到数组中。

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

正如@ T.Meyar所说 您正在调用BatchUpdates,但仍尝试向tableView添加单个indexPath。

"2018-07-18T16:07:33.047Z",  "info",  "SOAP createServiceRequest ack recieved & is successful.",  "ac710dc0-8aa4-11e8-a08c-0d98209bb4f5",  "2018-07-18T12:07:33.082-04:00",  "Accepted"

我认为您必须为BatchUpdates添加后备,因为iOS 10不支持BatchUpdates,因此您必须像之前在for循环之间那样使用for循环

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