-
-
Save amleszk/d80f06729a639a8b0672 to your computer and use it in GitHub Desktop.
Core data queue confinement
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
///Somewhere in application startup, where you setup a core data stack | |
NSOperationQueue *coreDataSerialOperationQueue; | |
coreDataSerialOperationQueue = [[NSOperationQueue alloc] init]; | |
[coreDataSerialOperationQueue setMaxConcurrentOperationCount:1]; | |
///All core data operations should be wrapped in this method for safety | |
+ (RCOperation *) addCoreDataOperation:(void (^)(void))coreDataOperation | |
{ | |
NSAssert(coreDataSerialOperationQueue,@"coreDataSerialOperationQueue was nil"); | |
NSParameterAssert(coreDataOperation); | |
NSOperation *operation = [[NSOperation alloc] init]; | |
[operation addExecutionBlock:coreDataOperation]; | |
[coreDataSerialOperationQueue addOperation:operation]; | |
return operation; | |
} | |
///Usage somewhere in a UI callback | |
NSManagedObjectContext *context = comment.managedObjectContext; | |
[RCCoreData addCoreDataOperation:^{ | |
//Note: wait for completion in the context of this operation | |
[context performBlockAndWait:^{ | |
[comment setAPIVote:vote]; | |
NSError *error; | |
[context save:&error]; | |
//Handle error | |
//And if the save needs to be propagated to a persistent store | |
[context.parentContext save:&error]; | |
//Handle error | |
}]; | |
}]; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment