Core data queue confinement
///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