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
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.
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.