首页 > 解决方案 > 将行插入不同的段时出现核心数据错误

问题描述

我有一张桌子,上面有早课和晚课两部分。我正在获取早晚课程的数据并将它们附加到以下变量

   var morClasses = [String]()
   var eveClasses = [String]()

然后,我将它们显示如下,

 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        var partOfDay = 0
        switch (segView.selectedSegmentIndex)
        {
        case 0:
            partOfDay = morClasses.count
            break
        case 1:
            partOfDay = eveClasses.count
            break
        default:break
        }
        return partOfDay
    }


func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
    let cell1 = tableView.dequeueReusableCell(withIdentifier: "tableViewCell") as! TableViewCell
    let cell2 = tableView.dequeueReusableCell(withIdentifier: "tableViewCellEve") as! TableViewCellEve

    switch (segView.selectedSegmentIndex)
    {
    case 0:
        cell1.label?.text  = morClasses[indexPath.row]

    case 1:
        cell2.label?.text  = eveClasses[indexPath.row]
        return cell2
    default: break
    }
    return cell1
    }

我使用 FRC 插入它们,如下所示,

func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
case NSFetchedResultsChangeType.insert:

    var indexPathToInsert = IndexPath(row: newIndexPath!.row, section: 0)
    let classDetailInsert  = fetchedResultsController.object(at: indexPathToInsert) as! ClassDetail
    let numbers = classDetailInsert.dayPart
    let containsMor = numbers!.contains(where: { $0 == 0 })
    let containsEve = numbers!.contains(where: { $0 == 1 })

    var rowToInsert = 0
    var rowToInsertEve = 0

    if (containsMor == true)
    {
        //if-else condition because count is updating N-1 late
        if (morClasses.count >= 1)
        {
            rowToInsert = morClasses.count
        }
        else
        {
            rowToInsert = 0
        }
        indexPathToInsert = IndexPath(row:rowToInsert, section: 0)
        morClasses.insert(classDetailInsert.title!, at: indexPathToInsert.row)
    }

    if (containsEve == true)
    {
        if (eveClasses.count >= 1)
        {
            rowToInsertEve = eveClasses.count
        }
        else
        {
            rowToInsertEve = 0
        }
        indexPathToInsert = IndexPath(row:rowToInsertEve, section: 0)
        eveClasses.insert(classDetailInsert.title!, at: indexPathToInsert.row)
    }
    self.tableView.insertRows(at: [indexPathToInsert], with: .fade)

一切正常,只要我在一个段中插入数据,但如果我添加与另一段有关的数据,我会收到以下错误。也就是说,我可以继续添加早间课程而不会出现任何错误,但是一旦我添加了晚间课程,就会出现以下错误。

CoreData:故障:严重的应用程序错误。在调用 -controllerDidChangeContent: 期间,从 NSFetchedResultsController 的委托中捕获了一个异常。无效更新:第 0 节中的行数无效。更新后现有节中包含的行数 (1) 必须等于更新前该节中包含的行数 (1),加上或减去数字从该部分插入或删除的行数(1 插入,0 删除)加上或减去移入或移出该部分的行数(0 移入,0 移出)。与用户信息(空)

我不知道我在哪里搞砸了,任何方向的帮助将不胜感激。

标签: iosswiftuitableviewcore-datansfetchedresultscontroller

解决方案


推荐阅读