Search code examples
iosobjective-ccore-datansmanagedobjectcontextwatchkit

Real time sync of Core Data between WatchKit and the app


I am writing a WatchKit extension for an iPhone application. I share Core Data using App Groups. This is working, the data is shared. Now I want to refresh data inside the iPhone app if the app is running in the foreground and a new database entry is added from the watch to the database. To track that I subscribed to NSManagedObjectContextDidSaveNotification

[[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(mergeChanges:)
                                                     name:NSManagedObjectContextDidSaveNotification
                                                   object:nil];
        }
    }

merge method:

- (void)mergeChanges:(NSNotification *)notification {
    if(notification.object != self.managedObjectContext) {
        [self performSelectorOnMainThread:@selector(updateMainContext:) withObject:notification waitUntilDone:NO];
    }
}

update main context method:

- (void)updateMainContext:(NSNotification *)notification {
    assert([NSThread isMainThread]);
    [self.managedObjectContext mergeChangesFromContextDidSaveNotification:notification];
}

I am trying to test it on the simulator (by running the iPhone and Watch simulator simultaneously) , but unfortunately NSManagedObjectContextDidSaveNotification is not called.

Is it actually possible to test it on the simulator? If yes, is this the right approach?


Solution

  • You can't use NSNotificationCenter since the iOS app and extension are different processes. Look at using MMWormhole to post your own notifications between the processes. You can listen for the NSManagedObjectContextDidSaveNotification in your extension and iOS app and then use MMWormhole to let the other process know about the notification. Also, you will need to manually refresh your managed data objects (See [NSManagedObjectContext refreshObject:(NSManagedObject *)object mergeChanges:(BOOL)flag]).