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

haemi commented Feb 20, 2016

is the foreground save really correct this way? The object changes the managedObjectContext, doesn't it?

@jklp
Copy link

jklp commented May 9, 2016

@haemi You're half correct - calling saveWithBlockAndWait: may or may not create a new Managed Object Context (MOC) - but it shouldn't matter as after the block is run the changes will be propagated back to the MR_default MOC.

What it does mean is calling saveWithBlockAndWait: is not thread safe, so be careful if calling from multiple places.

More info about threading (related to GCD) by the author below:

http://saulmora.com/coredata/magicalrecord/2013/09/15/why-contextforcurrentthread-doesn-t-work-in-magicalrecord.html

@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