NSFetchedResultsController Crash
-
07-07-2019 - |
Question
Following steps result in a crash in NSFetchedResultsController.
- I try to add the first element to a NSFetchedResultsController backed TableView.
- I create a temporary MO object and display a Modal View pane to add new object.
- On the Add Sheet (a Modal View Controller), I press Cancel Button to discard the new element.
- In the CancelAction callback for Cancel button, I delete the new temporary object I created.
- The code till here is exactly similar to Apple sample code for Core Data. The only extra code I have is a call to [tableView reloadData] after the Add sheet is dismissed.
- The crash results only if I try to add the first element, since it is related to wrong section count in NSFetchedResultsController.
This results in a crash given below. If I remove redundant call to reloadData, the crash is not visible. If I add a reloadData call to Recipe sample code data, the crash happens there as well.
Is it a known problem with NSFetchedResultsController?
2009-09-13 18:22:45.600 Recipes[14926:20b] * Terminating app due to uncaught exception 'NSRangeException', reason: '* -[NSCFArray objectAtIndex:]: index (0) beyond bounds (0)'
Solution
As you discovered by yourself, you should NOT use [tableView reloadData], because you are probably using the NSFetchedResultsController delegate methods
– controllerWillChangeContent:
– controller:didChangeObject:atIndexPath:forChangeType:newIndexPath:
– controller:didChangeSection:atIndex:forChangeType:
– controllerDidChangeContent:
These methods are actually in charge of updating your table view when you add, delete or modify objects. Therefore, when you add the call to [tableView reloadData] what happens is that two different threads are both accessing/modifying your table view. This causes the crash you are experiencing.
If you are not using the delegate methods, then the crash is due to something else in your code.