微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

NSFetchedResultsController的节数无效

如何解决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 举报,一经查实,本站将立刻删除。