Search code examples
core-dataobjective-c-blocksmagicalrecordmagicalrecord-2.2

Use saved item in save completion Magical Record


I would like to use the item that has been just been saved in the completion block of Magical Record saveWithBlock method. For example:

//Get the ID of an existing NSManagedObject to use in the save block (if it exists)
NSManagedObjectID *objectRef = [self.object objectID];

[MagicalRecord saveWithBlock:^(NSManagedObjectContext *localContext){
    //This method either loads an existing object and makes changes or creates  a new entity in localContext
   NSManagedObject *itemToSave = [self prepareItemInContext:localContext WithID: objectRef];
 } completion:^(BOOL success, NSError *error) {
     if (success) {
          //here I want to get at the object 'itemToSave' that was either created in the save block (with a new objectID) or updated (with the ID objectRef)

Solution

  • Well, you need to have a reference to your external context to load the object with that ID:

    NSManagedObjectContext *outsideContext = //...
    NSManagedObjectID *objectID = //...
    
    [MagicalRecord saveWithBlock:^(NSManagedObjectContext *localContext) {
    
    } completion:^(BOOL success, NSError *error) {
    
        NSManagedObject *newlySavedObject = [outsideContext existingObjectWithID:objectID];
        //...do stuff here
    }];
    

    Generally, however, I would discourage this usage. I would instead recommend keeping any predicates or means of reloading your data set handy, and dump and refetch fresh data from the store. This will give you proper object references. Another, more precise way of updating objects in other contexts is to listen to the NSManagedObjectContextDidSaveNotification and merge this updates into your context. From there, your data will be "refreshed" and as long as you're KVO'ing a property, or using a NSFetchedResultsController with a delegate, your updates will propagate to the UI (or other destination).