6

I'm using an NSFetchedResultsController to populate and manage my tables data source.

When a user picks a certain row, an actionsheet pops up and then lets the user change a value for that row:

NSManagedObject *managedObject = [fetchedResultsController objectAtIndexPath:selectedRowIndexPath];
[managedObject setValue:status forKey:@"status"];

This works really well and I can see the changes immediately in the tableview. This means that the NSFetchedResultsController knows something is changed and therefore reloads that tableviewcell. When I stop and quit my app (completely) then reopen it, the change is not saved.

I would think NSFetchedResultsConroller takes care of saving changes.

Do I need to save manually using the following code after every change?

// Save the context.
NSError *error = nil;
if (![self.managedObjectContext save:&error]) {
    NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
    abort();
}

Or maybe call this code in:

- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject 
       atIndexPath:(NSIndexPath *)indexPath 
     forChangeType:(NSFetchedResultsChangeType)type 
      newIndexPath:(NSIndexPath *)newIndexPath

1 Answer 1

6

You are correct. You need to manually save the context to the store. NSFetchedResultsController grabs data from the context, but does not save data to the store.

3
  • So it is not a bad idea to save inside the 'didChangeObject' delegate method?
    – Pieter
    Mar 14, 2012 at 12:59
  • 1
    If you did that you could risk a loop. NSFetchedResultsController delegate methods are used to update the view, not the model. So whenever something is saved to the context, the view is updated accordingly (basically so you don't have to keep reloading the table view). If you were to save to context in the delegate method, the delegate method would then keep firing because it would notice a change in the context.
    – Gobot
    Mar 14, 2012 at 13:05
  • So what's the solution?
    – fatuhoku
    Apr 4, 2014 at 23:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.