views:

625

answers:

1

Following steps result in a crash in NSFetchedResultsController.

  1. I try to add the first element to a NSFetchedResultsController backed TableView.
  2. I create a temporary MO object and display a Modal View pane to add new object.
  3. On the Add Sheet (a Modal View Controller), I press Cancel Button to discard the new element.
  4. In the CancelAction callback for Cancel button, I delete the new temporary object I created.
  5. 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.
  6. 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)'

+2  A: 

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.

unforgiven
I have set the delegate for NSFetchedResultsController, but I do not have these functions implemented as of yet. If I remove the delegate, the problem disappears. So this confirms the behavior.Are there any docs which talks about NSFetchedResultsController in more detail than the API docs? I did not see this behavior mentioned there. Please let me know and thanks for all the help.
siasl
Unfortunately, to the best of my knowledge, there are no other docs besides the API ones (at least no other docs related to the observed behavior). What I said is based on my personal experience.
unforgiven