NSFetchedResultsControllerDelegate在错误的indexPath上动画删除

前提:我有一个符合NSFetchedResultsControllerDelegateUITableViewController 。 我还有一个获取的结果控制器和托管对象上下文作为控制器中的变量。 我的tableView显示一个表,其中包含来自获取结果控制器的一部分核心数据对象。

我想要实现的是滑动删除。 选择删除的对象实际上已删除,但错误的indexPath正在动画删除,我不知道为什么。 我目前有以下方法,我认为是相关的:

 // This method is being called in viewDidLoad, adding all of the CoreData objects to an array called fetchedResults. func performFetch() { do { try fetchedResultsController?.performFetch() fetchedResults = fetchedResultsController?.fetchedObjects as! [Date] } catch let error as NSError { print(error.localizedDescription) } } // tableViewDataSource methods override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { return true } override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { let objectToDelete = fetchedResults[indexPath.row] fetchedResultsController?.managedObjectContext.deleteObject(objectToDelete) print("commitEditingStyle-indexPath = \(indexPath)") do { try managedContext.save() } catch let error as NSError { print(error.localizedDescription) } } } // NSFetchedResultsControllerDelegate methods func controllerWillChangeContent(controller: NSFetchedResultsController) { self.tableView.beginUpdates() } func controller(controller: NSFetchedResultsController, didChangeObject object: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) { switch type { case .Delete: if let indexPath = indexPath { print("didChangeObject indexPath = \(indexPath)") tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } default: return } } func controllerDidChangeContent(controller: NSFetchedResultsController) { self.tableView.endUpdates() } 

如您所见,我打印tableView:commitEditingStyle的commitPath tableView:commitEditingStyle方法以及controller:didChangeObject方法。 以下是2个打印声明:

commitEditingStyle-indexPath = {length = 2,path = 0 – 3}

didChangeObject-indexPath = {length = 2,path = 0 – 0}

为什么didChangeObject方法拾取错误的indexPath? 当我滑动删除对象时,该对象将在适当的indexPath(在本例中为3 …)中删除,但动画删除的表视图单元格是indexPath 0(我的表视图中的第一个单元格)。 是什么赋予了?

从代码中删除fetchedResults所有用法。 您正在缓存FRC知道的初始对象集,但您没有跟踪该缓存中的添加或删除。 缓存也浪费内存,因为您总是可以从FRC获得您想要的内容,并且它还可以跟踪更改。

所以,您所看到的应该是看似随机的差异,并且是由于索引缓存数组和FRC之间的差异。 它们应该最初匹配,如果你只删除最后一项它应该没问题,但任何其他删除都会导致它们不同步。