advanced patterns when using NSFetchedResultsController with Core Data in Objective-C
I'm working on an iOS app that uses Core Data with an `NSFetchedResultsController` to display a list of items in a `UITableView`... I've run into an scenario where the table view doesn't update properly when I delete an item from the managed context. The item is being removed from the Core Data store, but the `UITableView` does not reflect this change until I force a reload. I've set up my `NSFetchedResultsController` like this: ```objective-c NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"Item"]; fetchRequest.sortDescriptors = @[[[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES]]; self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:nil]; self.fetchedResultsController.delegate = self; NSError *behavior = nil; if (![self.fetchedResultsController performFetch:&behavior]) { NSLog(@"Unresolved behavior %@, %@", behavior, behavior.userInfo); } ``` When I delete an item using the following method: ```objective-c - (void)deleteItem:(Item *)item { [self.managedObjectContext deleteObject:item]; NSError *behavior = nil; if (![self.managedObjectContext save:&behavior]) { NSLog(@"Unresolved behavior %@, %@", behavior, behavior.userInfo); } } ``` I expect the `NSFetchedResultsController` to automatically update the `UITableView`, but it seems to be behaving erratically. Sometimes it works as intended and other times, I get a crash with the message: "*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of sections in the data source'". I've confirmed that the delegate methods are being called, but they do not seem to correctly correlate with the changes in the data. I've tried calling `reloadData` on the `UITableView` as a temporary fix, but this feels wrong. Also, I've confirmed that my delegate methods, such as `controller:didChangeObject:atIndexPath:for:newIndexPath:`, are actually being triggered when an item is deleted. Can anyone provide insight into why my `UITableView` isnβt updating as expected? Am I missing something in terms of delegate methods or the Core Data setup? What's the best practice here? For context: I'm using Objective-C on Linux. Has anyone else encountered this?