Skip to content

Instantly share code, notes, and snippets.

@fahied
Forked from tonyarnold/mr-save-patterns.md
Created August 28, 2014 07:41
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 fahied/fb33d8beee6f59e660d3 to your computer and use it in GitHub Desktop.
Save fahied/fb33d8beee6f59e660d3 to your computer and use it in GitHub Desktop.

Common Save Patterns

Standard background save

Assuming that you don't care which NSManagedObjectContext is used, and you just want to make some changes and save them in the background, use the following method. 90% of the time, this is what you'll want.

NSManagedObjectSubclass *myObject = [NSManagedObjectSubclass MR_findFirst];

[MagicalRecord saveWithBlock:^(NSManagedObjectContext *localContext) {
  // Make changes to your managed objects here, create new objects, or delete existing objects
  // There's no need to call save within this block
  // This block is called on an unspecified background thread

  NSManagedObjectSubclass *myLocalObject = [myObject MR_inContext:localContext];

  // It's now safe to make changes to `myLocalObject`
  
} completion:^(BOOL success, NSError *error) {
  // Generally, you'll use this completion block to update your UI, or handle success/errors
  // This block is always called on the main thread
  
}];

Standard foreground save

If you need to save some changes, but need the save operation to block the current thread until it has finished writing to disk — use the following method:

NSManagedObjectSubclass *myObject = [NSManagedObjectSubclass MR_findFirst];

[MagicalRecord saveWithBlockAndWait:^(BOOL success, NSError *error) {
  // Make your changes here. 
  // This block will be called on the main thread. You can safely access objects from outside the block here: 

  [myObject MR_deleteEntity];

  // This method will not return until the save has completed
  
}];

// Do post processing here — maybe update the UI?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment