Whether we’re using a standard Core Data stack or a UIManagedDocument, we need to know when changes come in from iCloud. Changes will always come in asynchronously, and our NSManagedObjectContext won’t know about them. It is our responsibility to notify our NSManagedObjectContext of any incoming changes. To do that, we first need to listen for the change notification via the NSNotificationCenter.
| NSString *name = nil; |
| name = NSPersistentStoreDidImportUbiquitousContentChangesNotification; |
| NSManagedObjectContext *moc = [[self dataController] managedObjectContext]; |
| [center addObserver:self |
| selector:@selector(mergePSCChanges:) |
| name:name |
| object:[moc persistentStoreCoordinator]]; |
| } |
Just like with the UIDocumentStateChangedNotification for the UIManagedDocument, it’s a good idea to start listening for the NSPersistentStoreDidImportUbiquitousContentChangesNotification notifications after the Core Data stack (or UIManagedDocument) has been constructed. Therefore, we put the ‑addObserver: selector: name: object: call in the ‑contextInitialized method.
When the notification fires, it can be treated exactly as if a notification from an NSManagedObjectContext is coming in from another thread, as discussed in Chapter 6, Threading. Although the notification doesn’t contain actual NSManagedObject instances, it does contain NSManagedObjectID instances, and the NSManagedObjectContext knows how to consume them as well.
| - (void)mergePSCChanges:(NSNotification*)notification |
| { |
| NSManagedObjectContext *moc = [self managedObjectContext]; |
| [moc performBlock:^{ |
| [moc mergeChangesFromContextDidSaveNotification:notification]; |
| }]; |
| } |