Search code examples
iphoneobjective-cioscore-datansmanagedobjectcontext

iPhone iOS how to merge Core Data NSManagedObjectContext?


I'm trying to download some JSON objects in the background and am doing quite a bit of multi threading. Once the operation completes, I noticed that this assertion fails:

NSAssert([user.managedObjectContext isEqual:[AppUser managedObjectContext]],@"Different contexts");

How can I merge changes into the main context defined by [AppUser managedObjectContext] ?


Solution

  • In my situation, I'm using a subclass of RKObjectLoader and there's way too many threads and operations to keep track of what's going on. I found that the RKObjectStore can be asked nicely to merge changes for me by asking the loaded object to save itself. (before I was asking [AppUser managedObjectContext] to save itself, which was wrong)

    The correct solution involved asking the loaded object to save itself in its own context as follows:

    - (void)objectLoader:(RKObjectLoader*)objectLoader didLoadObjects:(NSArray*)objects {
    
        AppUser* user = nil;
        for (id object in objects)
        {
             user = object;
        }
        NSError* error = nil;
    
    
    /**this call fires the:    
    //    - (void)mergeChanges:(NSNotification *)notification
    within the rkmanagedobjectstore class and merges changes made in this background operation over to the main contxt
     */
     [[user managedObjectContext] save:nil];
    
    }