NFetchedResultsController delegate method didChangeContentWith is not called when deleted an item using UIDIffableDataSource tableview

I am trying to implement my existing coredata project using the UITableViewDiffableDataSource. My tableview is coupled using the NSFetchedResultsController and the corresponding delegate methods. I am able to list the data in the tableview using diffabledatasource. My datasource is declared with the generic types as below


UITableViewDiffableDataSource<String, NSManagedObjectID>


For enabling the editing mode in the tableview I subclassed the UITableViewDiffableDataSource. I can delete the cell from the tableview but not from my coreData. The code for deleting the cell is as below


override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
if let identifierToDelete = itemIdentifier(for: indexPath){
var snapshot = self.snapshot()
snapshot.deleteItems([identifierToDelete])
apply(snapshot)
}
}
}

The below NSFetchedResultsControllerDelegate method is not called when I delete the cell.

func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChangeContentWith snapshot: NSDiffableDataSourceSnapshotReference)

I am not sure whether this is the correct way of coupling diffabledatasource with NSFetchedResultscontroller. Any help will be appreciated. Thanks in advance

Replies

You shouldn't be editing the snapshot, instead edit the model. I.e. delete the managed Object as follows:


- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        NSManagedObjectContext *context = self.managedObjectContext;
        NSManagedObjectID *objectID = [self itemIdentifierForIndexPath:indexPath];
        Event *event = [context objectWithID:objectID];
        [context deleteObject:event];
        NSError *error = nil;
        if (![context save:&error]) {
            // Replace this implementation with code to handle the error appropriately.
            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            NSLog(@"Unresolved error %@, %@", error, error.userInfo);
            abort();
        }
    }
}

After deleting the object the

didChangeContentWith snapshot object will be called.


Note: You need to add a managedObjectContext property to your UITableViewDiffableDataSource subclass.