Search code examples
objective-ccore-datansmanagedobjectcontextnsnotificationcenter

NSManagedObjectContextDidSaveNotification best way to update the UI?


In my code i have an mainManagedObjectContext and a backgroundManagedObjectContext and its working great.

I moved all my save code to the backgroundManagedObjectContext and merging the differences between the contexts via NSManagedObjectContextDidSaveNotification.

Now I want to update my UI after NSManagedObjectContextDidSaveNotification. What is the best approach beside of a NSFetchedResultController to do this?

The changes in my object is visible via the debugger and I could use KVO for this, but IMHO it's a terrible idea. In my abstraction i got a Model to handle the database calls and it would be great when my Model also handling changes after merging the context.

What is the best approach to do this?


Solution

  • As has been pointed out, for table and collection views, the best bet is NSFetchedResultsControllerDelegate.

    Another mechanism is to register for this (or your custom) notification NSNotificationCenter, e.g. for the original notification:

    [[NSNotificationCenter defaultCenter] 
           addObserver:self 
              selector:@selector(updateUI:) 
                  name:NSManagedObjectContextDidChangeNotification 
                object:nil];
    

    Best do this in viewDidAppear. Don't forget to remove the observer in viewWillDisappear. Note that following the comment I am using the change notification rather than the save notification.

    In your non-table view controllers you should isolate the UI setup, similar to the boilerplate code for the fetched results controller delegate, which implements a method like configureCell:atIndexPath:. You can then simply call this setup routine when you get the notification without duplicating any code.