Skip to content

Instantly share code, notes, and snippets.

@amleszk
Last active August 29, 2015 14:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amleszk/d80f06729a639a8b0672 to your computer and use it in GitHub Desktop.
Save amleszk/d80f06729a639a8b0672 to your computer and use it in GitHub Desktop.
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