Created
July 24, 2012 05:15
-
-
Save alanjrogers/3168178 to your computer and use it in GitHub Desktop.
Shows how to merge a NSManagedObjectContextDidSaveNotification from a different PSC
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* When adding the persistent store to a PSC | |
pragmaOptions = [[NSDictionary alloc] initWithObjectsAndKeys:@"WAL", @"journal_mode", nil]; | |
storeOptions = [[NSDictionary alloc] initWithObjectsAndKeys:pragmaOptions, NSSQLitePragmasOption, nil]; | |
This will allow multiple readers, and at most writer to connect to the Sqlite DB. Default journalling only allows multiple readers OR 1 writer (ie. writing blocks all reading). | |
*/ | |
- (NSSet *)convertObjects:(NSSet *)objects toContext:(NSManagedObjectContext *)context { | |
NSCParameterAssert([context persistentStoreCoordinator] != nil); | |
NSMutableSet *mutableObjects = [NSMutableSet setWithCapacity:[objects count]]; | |
[objects enumerateObjectsUsingBlock:^(NSManagedObject* obj, BOOL *stop) { | |
NSURL *objectURI = [[obj objectID] URIRepresentation]; | |
NSManagedObjectID *objectID = [[context persistentStoreCoordinator] managedObjectIDForURIRepresentation:objectURI]; | |
NSManagedObject *object = [context objectWithID:objectID]; | |
[mutableObjects addObject:object]; | |
}]; | |
return mutableObjects; | |
} | |
- (void)mergeChangesFromRootContext:(NSNotification*)note { | |
if ([note object] == [self rootContext]) { | |
NSManagedObjectContext *mainContext = [self mainContext]; | |
[mainContext performBlock:^{ | |
NSDictionary *userInfo = [note userInfo]; | |
NSSet *insertedObjects = [self convertObjects:[userInfo objectForKey:NSInsertedObjectsKey] toContext:mainContext]; | |
NSSet *deletedObjects = [self convertObjects:[userInfo objectForKey:NSDeletedObjectsKey] toContext:mainContext]; | |
NSSet *updatedObjects = [self convertObjects:[userInfo objectForKey:NSUpdatedObjectsKey] toContext:mainContext]; | |
NSDictionary *newUserInfo = @{ NSInsertedObjectsKey: insertedObjects, NSDeletedObjectsKey: deletedObjects, NSUpdatedObjectsKey : updatedObjects }; | |
NSNotification *localNotification = [NSNotification notificationWithName:NSManagedObjectContextDidSaveNotification object:[self rootContext] userInfo:newUserInfo]; | |
[[self mainContext] mergeChangesFromContextDidSaveNotification:localNotification]; | |
}]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment