为什么要调用NSFetchedResultsControllerDelegate'changeObject'

时间:2016-05-31 04:47:59

标签: ios swift core-data nsfetchedresultscontroller

我正在使用一些在UITableView中实现NSFetchedResultsControllerDelegate的样板代码。当我从表视图中执行segue时,会调用此委托方法:

    func controller(controller: NSFetchedResultsController,
                didChangeObject anObject: AnyObject,
                atIndexPath indexPath: NSIndexPath?,
                forChangeType type: NSFetchedResultsChangeType,
                newIndexPath: NSIndexPath?) {

    guard let newIndexPath = newIndexPath else{
        fatalError("No indexPath received") // Gets to this line, thus causing a crash
    }
    switch(type){

    case .Insert:
        tableView.insertRowsAtIndexPaths([newIndexPath], withRowAnimation: .Fade)

    case .Delete:
        tableView.deleteRowsAtIndexPaths([newIndexPath], withRowAnimation: .Fade)

    case .Update:
        tableView.reloadRowsAtIndexPaths([newIndexPath], withRowAnimation: .Fade)

    case .Move:
        tableView.deleteRowsAtIndexPaths([newIndexPath], withRowAnimation: .Fade)
        tableView.insertRowsAtIndexPaths([newIndexPath], withRowAnimation: .Fade)
    }

}

它不断崩溃,因为参数'newIndexPath'传入了一个nil值。当我调用prepareForSegue时,我可以通过将fetchedResultsController变量(负责调用委托方法的变量)设置为nil来绕过这个。

为什么要在segue上调用此方法?我怎样才能传递正确的newIndexPath?我应该担心吗?看起来设置负责将此委托方法调用为nil的变量似乎是一种非常优雅的方法来处理这个问题。

1 个答案:

答案 0 :(得分:2)

当您的FRC代表收到.Delete更改时会发生这种情况:

  

newIndexPath插入或移动对象的目标路径(对于删除,此值为nil)。

https://developer.apple.com/library/ios/documentation/CoreData/Reference/NSFetchedResultsControllerDelegate_Protocol/#//apple_ref/occ/intfm/NSFetchedResultsControllerDelegate/controller:didChangeObject:atIndexPath:forChangeType:newIndexPath

您应该indexPath.Delete.UpdatetableView.deleteRowsAtIndexPaths .Move一起使用newIndexPath

.Insert部分tableView.insertRowsAtIndexPaths.Move使用fatal: Authentication failed for 'http://sgit.emuasa.es/jros/PruebaGit1.git/'