Skip to content

Instantly share code, notes, and snippets.

@tonyarnold
Last active October 21, 2023 00:55
Show Gist options
  • Save tonyarnold/4694673 to your computer and use it in GitHub Desktop.
Save tonyarnold/4694673 to your computer and use it in GitHub Desktop.
Common save patterns for use with MagicalRecord

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?
@sami4064
Copy link

sami4064 commented Aug 2, 2016

Is it guaranteed that completion block of saveWithBlock will execute after saving the object to all MOCs.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment