iOS8 Swift: deleteRowsAtIndexPaths crashes

前端 未结 2 604
挽巷
挽巷 2020-12-19 03:48

I am having some trouble with deleting a row from my tableView in Swift, iOS 8, Xcode 6 Beta 6. Every time I try to delete a row I get an error along the lines of

相关标签:
2条回答
  • 2020-12-19 04:07

    I believe this is simply a caching problem. Your fetchedResultController is not going to automatically refetch your results as it caches its results. That means that when tableView:numberOfRowsInSection: is called again, the results count is still returning 25 even though you deleted an item.

    0 讨论(0)
  • 2020-12-19 04:19

    It's easy to reproduce your crash with a Xcode Core Data Master-Detail template project. As a general rule, when you use NSFetchedResultsController, you should really use NSFetchedResultsControllerDelegate (you have declared it but don't use it).

    Delete those lines in your tableView:commitEditingStyle:forRowAtIndexPath: method:

    tableViewMain.beginUpdates()
    tableViewMain!.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: UITableViewRowAnimation.Fade)
    tableViewMain.endUpdates()
    

    And add those lines to your viewController class:

    func controllerWillChangeContent(controller: NSFetchedResultsController) {
        tableViewMain.beginUpdates()
    }
    
    func controller(controller: NSFetchedResultsController!, didChangeSection sectionInfo: NSFetchedResultsSectionInfo!, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) {
        switch type {
        case .Insert:
            tableViewMain.insertSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade)
        case .Delete:
            tableViewMain.deleteSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade)
        default:
            return
        }
    }
    
    func controller(controller: NSFetchedResultsController!, didChangeObject anObject: AnyObject!, atIndexPath indexPath: NSIndexPath!, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath!) {
        switch type {
        case .Insert:
            tableViewMain.insertRowsAtIndexPaths([newIndexPath], withRowAnimation: .Fade)
        case .Delete:
            tableViewMain.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
        case .Update:
            return
            //Should also manage this case!!!
            //self.configureCell(tableView.cellForRowAtIndexPath(indexPath), atIndexPath: indexPath)
        case .Move:
            tableViewMain.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
            tableViewMain.insertRowsAtIndexPaths([newIndexPath], withRowAnimation: .Fade)
        default:
            return
        }
    }
    
    func controllerDidChangeContent(controller: NSFetchedResultsController!) {
        tableViewMain.endUpdates()
    }
    

    This should fix your problem.

    0 讨论(0)
提交回复
热议问题