Search code examples
ioscore-datarubymotionmagicalrecord

How do I use Magical Record to create & update objects and save them without using contextForCurrentThread


I just read the author of MagicalRecord's blog post on Why contextForCurrentThread Doesn't work in MagicalRecord.

contextForCurrentThread is deprecated and saveWithBlock should be used instead because it creates a safe new NSManagedObjectContext for the relevant thread.

I've been using contextForCurrentThread extensively in my app so far. However, I'm having trouble figuring out how to use saveWithBlock instead as my fetching and saving are not necessarily happening sequentially.

Currently I'm doing things like:

localContext = NSManagedObjectContext.MR_contextForCurrentThread
person = Person.MR_createInContext(localContext)
person.name = "John Smith"

The user may then browse around the app, different controllers, views etc. are displayed. Other objects may be created using a similar method to the code above.

Then at some arbitrary point in the future, when the user decides to save, I run this method:

localContext = NSManagedObjectContext.MR_contextForCurrentThread
localContext.MR_saveToPersistentStoreWithCompletion(
  lambda { |success, error|
    # ...
  }
)

What is the recommended way to create & update objects and then save them without using contextForCurrentThread?


Solution

  • So, I use objective C as opposed to RubyMotion, but you should be able todo things like this:

    MagicalRecord.saveWithBlock(
       lambda { |localContext|
           person = Person.MR_createInContext(localContext)
           #update person stuff here
       }
    )
    

    EDIT

    If you want to save the context later, you just need to hold on to it:

    // Somewhere in your ViewController, etc
    NSManagedObjectContext *context = [NSManagedObjectContext MR_confinementContext];
    
    
    // Somewhere else
    Person *p = [Person MR_createInContext:context];
    
    // And in yet another method
    [context MR_saveToPersistentStoreAndWait];
    

    The main idea here is that you just need to hold on to the context and perform your operations on it when you're ready. If you want a background save to occur, you an use the following method:

    [context MR_saveToPersistentStoreCompletion:^(BOOL success, NSError *error){
       //called on the main thread when save is complete
    }];