Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I share a Core Data store between processes using NSDistributedNotifications?

Background

I've already posted a question about the basics of sharing a Core Data store between processes.

I'm trying to implement the recommendations given and I'm running into problems.

My Goal

I have two processes - the Helper App and the UI. They both share a single data store. I want the UI to update it's NSManagedObjectContext when the Helper App has saved new data to the store.

Current Program Flow

  1. The Helper App Process writes data to the Store.

  2. In the Helper App, I listen for NSManagedObjectContextDidSaveNotification notifications.

  3. When the context is saved, I encode the inserted, deleted and updated objects using their URI representations and NSArchiver.

  4. I send an NSNotification to the NSDistributedNotificationCenter with this encoded dictionary as the userInfo.

  5. The UI Process is listening for the save notification. When it receives the notification, it unarchives the userInfo using NSUnarchiver.

  6. It looks up all the updated/inserted/deleted objects from the URIs given and replaces them with NSManagedObjects.

  7. It constructs an NSNotification with the updated/inserted/deleted objects.

  8. I call mergeChangesFromContextDidSaveNotification: on the Managed Object Context of the UI Process, passing in the NSNotification I constructed in the previous step.

The Problem

Inserted objects are faulted into the UI Managed Object Context fine and they appear in the UI. The problem comes with updated objects. They just don't update.

What I've tried

  1. The most obvious thing to try would be to pass the save Notification from the Helper App process to the UI process. Easy, right? Well, no. Distributed Notifications won't allow me to do that as the userInfo dictionary is not in the right format. That's why I'm doing all the NSArchiving stuff.

  2. I've tried calling refreshObject:mergeChanges:YES on the NSManagedObjects to be updated, but this doesn't seem to have any effect.

  3. I've tried performing the mergeChangesFromContextDidSaveNotification: selector on the main thread and the current thread. Neither seems to affect the result.

  4. I've tried using mergeChangesFromContextDidSaveNotification: before between threads, which of course is much simpler and it worked perfectly. But I need this same functionality between processes.

Alternatives?

Am I missing something here? I'm consistently getting the feeling I'm making this much more complex than it needs to be, but after reading the documentation several times and spending a few solid days on this, I can't see any other way of refreshing the MOC of the UI.

Is there a more elegant way of doing this? Or am I just making a silly mistake somewhere in my code?

The Code

I've tried to make it as readable as possible, but it's still a mess. Sorry.

Helper App Code

   -(void)workerThreadObjectContextDidSave:(NSNotification *)saveNotification {
        NSMutableDictionary *savedObjectsEncodedURIs = [NSMutableDictionary dictionary];
        NSArray *savedObjectKeys = [[saveNotification userInfo] allKeys];

        for(NSString *thisSavedObjectKey in savedObjectKeys) {
            // This is the set of updated/inserted/deleted NSManagedObjects.
            NSSet *thisSavedObjectSet = [[saveNotification userInfo] objectForKey:thisSavedObjectKey];
            NSMutableSet *thisSavedObjectSetEncoded = [NSMutableSet set];

            for(id thisSavedObject in [thisSavedObjectSet allObjects]) {
                // Construct a set of URIs that will be encoded as NSData
                NSURL *thisSavedObjectURI = [[(NSManagedObject *)thisSavedObject objectID] URIRepresentation];
                [thisSavedObjectSetEncoded addObject:thisSavedObjectURI];
            }
            // Archive the set of URIs.
            [savedObjectsEncodedURIs setObject:[NSArchiver archivedDataWithRootObject:thisSavedObjectSetEncoded] forKey:thisSavedObjectKey];
        }

        if ([[savedObjectsEncodedURIs allValues] count] > 0) {
            // Tell UI process there are new objects that need merging into it's MOC
            [[NSDistributedNotificationCenter defaultCenter] postNotificationName:@"com.synapticmishap.lapsus.save" object:@"HelperApp" userInfo:(NSDictionary *)savedObjectsEncodedURIs];
        }
    }

UI Code

-(void)mergeSavesIntoMOC:(NSNotification *)notification {
    NSDictionary        *objectsToRefresh        = [notification userInfo];
    NSMutableDictionary *notificationUserInfo    = [NSMutableDictionary dictionary];
    NSArray *savedObjectKeys = [[notification userInfo] allKeys];

    for(NSString *thisSavedObjectKey in savedObjectKeys) {
        // Iterate through all the URIs in the decoded set. For each URI, get the NSManagedObject and add it to a set.
        NSSet *thisSavedObjectSetDecoded = [NSUnarchiver unarchiveObjectWithData:[[notification userInfo] objectForKey:thisSavedObjectKey]];
        NSMutableSet *savedManagedObjectSet = [NSMutableSet set];

        for(NSURL *thisSavedObjectURI in thisSavedObjectSetDecoded) {
            NSManagedObject *thisSavedManagedObject = [managedObjectContext objectWithID:[persistentStoreCoordinator managedObjectIDForURIRepresentation:thisSavedObjectURI]];
            [savedManagedObjectSet addObject:thisSavedManagedObject];
            // If the object is to be updated, refresh the object and merge in changes.
            // This doesn't work!
            if ([thisSavedObjectKey isEqualToString:NSUpdatedObjectsKey]) {
                [managedObjectContext refreshObject:thisSavedManagedObject mergeChanges:YES];
                [managedObjectContext save:nil];
            }
        }
        [notificationUserInfo setObject:savedManagedObjectSet forKey:thisSavedObjectKey];
    }
    // Build a notification suitable for merging changes into MOC.
    NSNotification *saveNotification = [NSNotification notificationWithName:@"" object:nil userInfo:(NSDictionary *)notificationUserInfo];
    [managedObjectContext performSelectorOnMainThread:@selector(mergeChangesFromContextDidSaveNotification:)
                                    withObject:saveNotification
                                 waitUntilDone:YES];
}
like image 316
John Gallagher Avatar asked Nov 29 '09 13:11

John Gallagher


2 Answers

I used the method in

http://www.mlsite.net/blog/?p=518

then every object is correctly faulted but the faults are fetch in cache so still no update

I had to do [moc stalenessInterval = 0];

And it finally worked, with relationship.

like image 123
Wid Avatar answered Oct 12 '22 23:10

Wid


You're looking for - (void)refreshObject:(NSManagedObject *)object mergeChanges:(BOOL)flag I believe.

This will refresh the object with the info in the persistent store, merging changes if you want.

like image 37
Ben Lachman Avatar answered Oct 13 '22 01:10

Ben Lachman