NSFetchedResultsController的节数无效

问题描述

我正在使用NSFetchedResultsController来管理tableView数据源,但是当我尝试添加实体时,它一直崩溃,这给了我这个错误Terminating app due to uncaught exception 'NSInternalInconsistencyException',reason: 'Invalid update: invalid number of sections. The number of sections contained in the table view after the update (1) must be equal to the number of sections contained in the table view before the update (0),plus or minus the number of sections inserted or deleted (0 inserted,0 deleted).'

执行此代码时发生错误

let exercisetoAdd = Workout_Exercise(context: DataController.shared.context)
        exercisetoAdd.name = exercise
        exercisetoAdd.exerciseIndex = Int16((currentWorkout?.exercises?.allObjects.count)! + 1)
        let firstemptySet = CDSet(context: DataController.shared.context)
        exercisetoAdd.addToSets(firstemptySet)
        currentWorkout.addToExercises(exercisetoAdd)

为实体CDSet设置了NSFetchedResultsController,我敢肯定我已经拥有所有必需的协议存根:

func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
    tableView.beginUpdates()
}

func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
    tableView.endUpdates()
}

func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>,didChange anObject: Any,at indexPath: IndexPath?,for type: NSFetchedResultsChangeType,newIndexPath: IndexPath?) {
    switch type {
    case .insert:
        tableView.insertRows(at: [newIndexPath!],with: .fade)
    case .delete:
        tableView.deleteRows(at: [newIndexPath!],with: .fade)
    default:
        break
    }
}

func numberOfSections(in tableView: UITableView) -> Int {
    if let sections = fetchedResultsController.sections?.count {
        return sections
    } else {
        return 0
    }
}

func tableView(_ tableView: UITableView,numberOfRowsInSection section: Int) -> Int {
    if let rows = fetchedResultsController.sections?[section].numberOfObjects {
        return rows
    } else {
        return 0
    }
}

这是我正在使用的提取请求:

    let fetchRequest:NSFetchRequest<CDSet> = CDSet.fetchRequest()
    fetchRequest.sortDescriptors = [NSSortDescriptor(key: "exercise",ascending: false)]
    fetchRequest.predicate = nspredicate(format: "exercise.workout == %@",currentWorkout)
    
    fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest,managedobjectContext: DataController.shared.context,sectionNameKeyPath: "exercise",cacheName: nil)
    fetchedResultsController.delegate = self
    
    do {
        try fetchedResultsController.performFetch()
    } catch {
        
    }

我不知道是什么原因导致了错误的发生,有人遇到过类似的问题并能够找到解决方案吗?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...