ppaulojr
ppaulojr

Reputation: 3647

NSFetchedResultsController:objectAtIndexPath: causes NSInvalidArgumentException

I'm using some classes to handle synchronization between Core Data and remote JSON services and in one of the classes, that manages the objects currently in Core Data, I'm getting several crashes, randomly.

Method

Class

 @interface XLLocalDataLoader() <NSFetchedResultsControllerDelegate>

    // private properties
    @property (strong, nonatomic) NSFetchedResultsController *fetchedResultsController;

Method

// get core data object at index path
-(NSManagedObject *)objectAtIndexPath:(NSIndexPath *)indexPath
{
    if ([indexPath row] < [self numberOfRowsInSection:indexPath.section]){
        return [self.fetchedResultsController objectAtIndexPath:indexPath];
    }
    return nil;
}

Source Code

The source code is available at GitHub -> XLDataLoader -> XLLocalDataLoader.

Error

Fatal Exception: NSInvalidArgumentException Object's persistent store is not reachable from this NSManagedObjectContext's coordinator

Already investigated

  1. NSFetchedResultsController crashes on objectAtIndexPath?
  2. NSFetchedResultsController objectAtIndexPath crash (EXC_BAD_ACCESS)
  3. NSFetchedResultsController Crash
  4. NSFetchedResultsController objectAtIndex, objectAtIndexPath, indexPathForObject inconsistencies
  5. Deleting last row in a section -> crash, using NSFetchedResultsController

Questions

  1. Are there some guidelines to try to reproduce and debug NSInvalidArgumentException?
  2. Any ideas about what I'm doing wrong?

Upvotes: 2

Views: 476

Answers (1)

Mundi
Mundi

Reputation: 80265

Using a fetched results controller in a "loader" class seems the wrong approach.

A fetched results controller is really meant to help you display Core Data content in a table view. Obviously, the normal use case is to run it on the main thread.

If you are fetching data from a web service and parsing it presumably in the success handler, this means it is on a different thread. You would have to use a separate context (typically a child context of the main context) and then save this context after you are done manipulating the data. This will push the changes up to the main context and the fetched results controller will be notified via the delegate.

The error message also seems to indicate that you are not managing the contexts correctly.

Upvotes: 2

Related Questions