NSFetchedResultsControllerDelegate在错误的indexPath上动画删除

时间:2015-10-26 04:51:23

标签: ios swift uitableview core-data nsfetchedresultscontroller

前提:我的NSFetchedResultsControllerDelegate符合tableView。我还有一个获取的结果控制器和托管对象上下文作为控制器中的变量。我的// 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() } 显示一个表,其中包含来自获取结果控制器的一部分核心数据对象。

我尝试实施的内容是轻扫以删除。选择删除的对象实际上已删除,但是错误的indexPath正在被动画删除,我不知道原因。我目前有以下方法,我认为是相关的:

tableView:commitEditingStyle

如您所见,我打印了controller:didChangeObject方法的indexPath以及didChangeObject方法。以下是2个打印陈述:

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

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

为什么$V{saldo} = -250000方法拾取了错误的indexPath?当我滑动删除对象时,对象将在正确的indexPath(在这种情况下为3 ...)中删除,但动画删除的表视图单元格是indexPath 0(我的表视图中的第一个单元格)。是什么给了什么?

1 个答案:

答案 0 :(得分:0)

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

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