0
votes

I built a tableview, with FRC to show data from core-data. I also implemented the controller didChange delegate, to view the changes in the core-data:

    func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {

        switch (type) {
        case .insert:
            if indexPath != nil && (indexPath?.row)! < (controller.fetchedObjects?.count)!{
                tableView.insertRows(at: [indexPath!], with: .left)
            }
            break;

        case .update:
            if indexPath != nil && (indexPath?.row)! < (controller.fetchedObjects?.count)!{
                self.tableView.reloadRows(at: [indexPath!], with: .left)
            }
            break;

        case .delete:
            if indexPath != nil && (indexPath?.row)! < (controller.fetchedObjects?.count)!{
                self.tableView.deleteRows(at: [indexPath!], with: .left)
            }
            break;

        case .move:
            if indexPath != nil && (indexPath?.row)! < (controller.fetchedObjects?.count)!{
                print("type.move: shouldn't get in here!")
            }
            break;

        }
    }

when I run I got this on the console:

*** Assertion failure in -[UITableView _endCellAnimationsWithContext:] CoreData: error: Serious application error. An exception was caught from the delegate of NSFetchedResultsController during a call to -controllerDidChangeContent:. Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (216) must be equal to the number of rows contained in that section before the update (215), plus or minus the number of rows inserted or deleted from that section (0 inserted, 0 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out). with userInfo (null)

although the app doesn't crash - but the tableview is screwed and doesn't show the date.

1
Seems you’ve updated the data (model) via the controller but you’ve not updating the view. I would be useful to see your code in the delegate method controllerDidChangeContent to help identify the issue. - andrewbuilder

1 Answers

3
votes

my mistake was that on insert and update I referred to indexPath instead of newIndexPath...

it should be:

        case .insert:
        if newIndexPath != nil && (newIndexPath?.row)! < (controller.fetchedObjects?.count)!{
            tableView.insertRows(at: [newIndexPath!], with: .left)
        }
        break;