Last active
August 29, 2015 14:04
-
-
Save sdarlington/0b1fe78ff466ea2f48d1 to your computer and use it in GitHub Desktop.
Using parent NSManagedObjectContexts seems like a pain...
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
@implementation NSManagedObjectContext (ParentContextHelper) | |
/* | |
* In sample code I see a lot of stuff like this when dealing with nested (parent) managed object contexts: | |
* | |
* [moc performBlock:^{ | |
* NSError* error = nil; | |
* [moc save:&error]; | |
* | |
* [moc.parentContext performBlock:^{ | |
* NSError* error = nil; | |
* moc.parentContext save:&error]; | |
* }]; | |
* }]; | |
* | |
* (Example: http://stackoverflow.com/questions/19452487/core-data-parent-context-and-change-propagation) | |
* | |
* The problem with this is that each context has to know where it is in relation to the | |
* root context (i.e., the one with the persistent store). | |
* | |
* The approach below seems a bit hacky but I don't (currently) see why it wouldn't work. Is there | |
* a better scheme? | |
* | |
*/ | |
- (void)propagateSave:(void (^)(NSError*))completionHandler { | |
__weak typeof(self) weakSelf = self; | |
[self propagateSave:completionHandler | |
withBlock:^(void (^block)(void)){ | |
[weakSelf performBlock:block]; | |
}]; | |
} | |
- (void)propagateSaveAndWait:(void (^)(NSError*))completionHandler { | |
__weak typeof(self) weakSelf = self; | |
[self propagateSave:completionHandler | |
withBlock:^(void (^block)(void)){ | |
[weakSelf performBlockAndWait:block]; | |
}]; | |
} | |
- (void)propagateSave:(void (^)(NSError *))completionHandler withBlock:(void (^)(void (^)(void)))blockName { | |
__weak typeof(self) weakSelf = self; | |
blockName(^{ | |
NSError* error = nil; | |
BOOL retv = [weakSelf save:&error]; | |
if (retv && weakSelf.parentContext) { | |
[weakSelf.parentContext propagateSave:completionHandler | |
withBlock:blockName]; | |
} | |
else if (completionHandler) { | |
completionHandler(error); | |
} | |
}); | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment