Search code examples
ioscocoa-touchmagicalrecord

proper way to save NSManagedContext with latest version of Magical Record


In order to save my current NSManagedObjectContext I use [localContext MR_saveNestedContexts]; but I get a warning that the method has been deprecated.

How should I save an NSManagedObjectContext with the latest version of Magical Record (literally pulled from GitHub today, Jul 19 2013).


Solution

  • Check out their documentation.
    https://github.com/magicalpanda/MagicalRecord/blob/master/Docs/Saving-Entities.md

    Try using

    - (void) MR_saveToPersistentStoreWithCompletion:(MRSaveCompletionHandler)completion;
    

    I'm not using the latest version of MagicalRecord, but I think this should be correct

        //get the context for the current thread
        //this context can be updated by anyone other process on this thread that uses the same MR_contextForCurrentThread call
        //it's a local store that can be merged to a parent store
        NSManagedObjectContext *localContext = [NSManagedObjectContext MR_contextForCurrentThread];
        
        //create an NSManagedObject of type YourEntity and insert it into the localContext object
        NSManagedObject *obj = [YourEntity MR_createInContext:localContext];
        
        //make any updates to obj
        
        //save the localContext async
        //this call should save all nested NSManagedObjectContexts as well (if they exist)
        [localContext  MR_saveToPersistentStoreWithCompletion:^{
            //when the async save is complete, this block gets executed
            //blocks work very similarly to javascript callbacks
            //basically it's a function reference or block of code that get's packaged up and can be passed around
            //In this case, the completion block allows to to run any code after the save has been completed.
        }];
    

    One thing I didn't realize when I started was when I created my entity, it also inserted it into the context. It caused me to accidentally save objects that I didn't need to persist. To avoid this I setup a subcontext and only save it when I want to persist the objects.

    self.context = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
    self.context.parentContext = [NSManagedObjectContext MR_defaultContext];