【发布时间】:2021-03-05 14:59:44
【问题描述】:
我正在使用 NSFetchedResultsController 来管理我的 tableView,问题是当添加另一个部分时,NSFetchedResultsController 自动将它放在索引 0 处,这导致我的应用程序出现了几个问题。下面是我如何设置我的 NSFetchedResultsController,我正在获取类型 CDSet,每个部分的类型都是 exercise
两者的关系如下
CDSet Exercise
如何按exercise.exerciseIndex 对部分进行排序?
let fetchRequest:NSFetchRequest<CDSet> = CDSet.fetchRequest()
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "set_index", ascending: true)]
fetchRequest.predicate = NSPredicate(format: "exercise.workout == %@", currentWorkout)
fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: DataController.shared.context, sectionNameKeyPath: "exercise.exerciseIndex", cacheName: nil)
fetchedResultsController.delegate = self
do {
try fetchedResultsController.performFetch()
} catch {
}
更新: 我已将 sortDescriptor 更新为以下内容:
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "exercise.exerciseIndex", ascending: true), NSSortDescriptor(key: "set_index", ascending: true)]
但现在尝试添加第二个部分时出现此错误:
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 (2) must be equal to the number of sections contained in the table view before the update (1), plus or minus the number of sections inserted or deleted (2 inserted, 0 deleted).'
当我只指定 1 时,不确定它为什么要插入 2
这是我的 NSFetchedResultsController 委托方法:
func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
tableView.beginUpdates()
}
func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
tableView.endUpdates()
}
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange sectionInfo: NSFetchedResultsSectionInfo, atSectionIndex sectionIndex: Int, for type: NSFetchedResultsChangeType) {
let indexPath = IndexPath(row: 0, section: sectionIndex)
let indexSet = IndexSet(indexPath)
tableView.insertSections(indexSet, with: .fade)
}
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
}
}
【问题讨论】:
-
那么为什么不根据
excercise.index(或任何要排序的值)和set_index进行排序呢?
标签: ios swift core-data nsfetchedresultscontroller