Last active
August 29, 2015 13:58
-
-
Save evanlaird/9934664 to your computer and use it in GitHub Desktop.
Asynchronously save up the parent-child chain of NSManagedObjectContexts to disk
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
- (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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.