When we first added Core Data to our app, the tutorial we followed created an NSManagedObjectContext in our app delegate. It recommended that if we used Core Data on other threads, we should add an observer to update our main context when the thread’s context was saved, like so:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(mergeChanges:)
name:NSManagedObjectContextDidSaveNotification
object:self.managedObjectContext];
This happens once in applicationDidFinishLoadingWithOptions:. However, the documentation for NSManagedObjectContext says:
Several system frameworks use Core Data internally. If you register to receive these notifications from all contexts (by passing nil as the object parameter to an addObserver… method), then you may receive unexpected notifications that are difficult to handle.
This suggests to me that the object parameter ought to be the context that’s being saved (in my case the background context) rather than the main context. Is that the case? Do I need to observe NSManagedObjectContextDidSaveNotification from every NSManagedObjectContext I create?
Simon,
The object in the
-addObserver:selector:name:object:method is the source of the notifications. In your case, it should be the backgroundNSManagedObjectContext.Should you observe every context you create? As in all things, that depends. For example, sometimes you want to use a context as a scratchpad and will never save anything from it. Why bother to observe it? In general, you want to observe any contexts that mutate the persistent store.
Andrew