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

Paul Sturgess picture Paul Sturgess · Oct 8, 2013 · Viewed 21.7k times · Source

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?

Answer

lbsweek picture lbsweek · Jan 11, 2014

here is a tutorial for new api: http://ablfx.com/blog/article/2 here is the refence: http://cocoadocs.org/docsets/MagicalRecord/2.1/

  1. init

    [MagicalRecord setupCoreDataStackWithStoreNamed:@"MyDatabase.sqlite"];

  2. dealloc

    [MagicalRecord cleanUp];

  3. insert

    Person *alex = [Person MR_createEntity]; alex.name = @"Alex"; alex.age = @23;

  4. select

    /Retrieve all for aNSManagedObject subclass NSArray *people = [Person MR_findAll];

    //Retrieve first record Person *aPerson = [Person MR_findFirst];

    //Retrieve records conditionally & sort NSArray *people = [Person MR_findByAttribute:@"name" withValue:@"alex" andOrderBy:@"age" ascending:YES];

  5. update

    //Updating a retrieved entity is as easy as manipulating it's properties aPerson.age = @56;

  6. delete

    //Remove all records [Person MR_truncateAll];

    //Delete single record, after retrieving it [alex MR_deleteEntity];

  7. save

    //For any entities to actually be saved / updated / deleted on disk call following method [[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreAndWait];

    //Again check the MagicalRecord repo for more save options