Skip to content

Instantly share code, notes, and snippets.

@Blackjacx
Last active August 29, 2015 14:12
Show Gist options
  • Save Blackjacx/7c51ece9a6ba513ec23c to your computer and use it in GitHub Desktop.
Save Blackjacx/7c51ece9a6ba513ec23c to your computer and use it in GitHub Desktop.
Core Data Managed Object Creation using Magical Record
/*
Create a temporary context with the default context as parent.
The state of the default context will be available in the temporary context.
If you are really sure you want to save the object you don't need to create a temporary context.
You can use MR_defaultContext in this case.
*/
NSManagedObjectContext *tempContext = [NSManagedObjectContext MR_contextWithParent:[NSManagedObjectContext MR_defaultContext]];
/*
Perform operations on the temporary context on the
main thread (performBlockAndWait:) or
asynchromously (performBlock:)
*/
[tempContext performBlockAndWait:^{
/*
Propagete the context to the parser handler so it can be used for object creation.
*/
SHManagedObject *managedObject = [SHParserHandler parseManagedObject:(NSDictionary *) responseObject usingContext:tempContext];
/*
Do some operations on the newly created object in the temporary context.
*/
BOOL result = /* the result of the operation on the managedObject */
/*
If some condition is fulfilled you want to save the context and therefore all changes you made in that context.
The changes will be saved to the persistent store and therefore are saved to disk.
*/
if (result) {
[tempContext MR_saveToPersistentStoreWithCompletion:^(BOOL success, NSError *error) {
/*
Don't forget to check the error once by using asserts to be shure to detect all programming errors during development
and by checking the error in an if to handle success state only if the error is nil.
If an error occurs you most probably misuse Core Data somewhere in your code.
Read the error description carefully and find out why it produces the error!
*/
NSAssert(error, @"Error Saving: %@", error);
if(error) {
/*
handle the error state.
*/
}
else {
/*
handle the success state.
*/
}
}];
}
}];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment