Skip to content

Instantly share code, notes, and snippets.

@evanlaird
Last active August 29, 2015 13:58
Show Gist options
  • Save evanlaird/9934664 to your computer and use it in GitHub Desktop.
Save evanlaird/9934664 to your computer and use it in GitHub Desktop.
Asynchronously save up the parent-child chain of NSManagedObjectContexts to disk
- (BOOL)saveToDiskAndShouldWait:(BOOL)wait {
__block BOOL success = NO;
// Give self time to save
[self performBlockAndWait:^{
success = [self saveOrLogError];
}];
NSManagedObjectContext *parent = [self parentContext];
if (parent) {
if (wait) {
[parent performBlockAndWait:^{
[parent saveToDiskAndShouldWait:wait];
}];
} else {
[parent performBlock:^{
[parent saveToDiskAndShouldWait:wait];
}];
}
}
return success;
}
@evanlaird
Copy link
Author

Posting here to remember. I wrote this method to be able to pass -saveContext messages up the parent-child chain of NSManagedObjectContexts, up to the final one which was a background context. This unloads disk IO off of the main thread.

If wait is NO, then the message to save recurses up the chain, but the caller returns to its execution context. -performBlock and -performBlockAndWait execute in the callee's thread of execution.

Based on Marcus Zarra's implementation of -(void)saveContext:(BOOL)wait, from Core Data 2nd Edition, p96. The implementation above improves upon this idea by not needing to care about how many parents a given context has, and can effectively do asynchronous saves all the way up the stack.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment