Search code examples
ioscore-datansmanagedobjectcontext

Core Data and Managed Object Contexts


I'm new with Core Data and I have some questions about how to do the things in the right way. I think I need a temporaryManagedObjectContext to work with temporary entities, while user is editing a new entity. When user tap save that data I want to insert those entities in the persistedManagecObjectContext and then saveContext. What is the best practice to achieve this? Since I don't want to save in the temp context, it is mandatory to use threading?

Thanks for your knowledge!


Solution

  • You need to merge the changes in the temporary ManagedObjectContext (MOC) into the persisted one. This is an example of how I achieved this. Im using threading (One MOC per thread), but Im pretty sure it should work out fine without threads aswell.

    You call this method to save your changes in the tempMOC:

    - (void) saveNewEntry {
        NSNotificationCenter *dnc = [NSNotificationCenter defaultCenter];
    
        // Subscribe to "NSManagedObjectContextDidSaveNotification"
        // ..which is sent when "[tempMOC save];" is called.
        [dnc addObserver: self 
                selector: @selector(mergeChanges:) 
                    name: NSManagedObjectContextDidSaveNotification 
                  object: tempMOC];
    
        // Save changes
        [tempMOC save];
    
        // Remove subscribtion
        [dnc removeObserver: self 
                       name: NSManagedObjectContextDidSaveNotification 
                     object: tempMOC];
    
    }
    

    ...which will fire off a notification to:

    - (void) mergeChanges: (NSNotification*) saveNotification {
    
        // If youre using threads, this is necessary:
        [self performSelectorOnMainThread: @selector(mergeToMainContext:) 
                               withObject: saveNotification 
                            waitUntilDone: NO]; 
    
        // ...otherwise, you could do the merge in this method
        // [persistedMOC mergeChangesFromContextDidSaveNotification: saveNotification];
    }
    

    ...which in turn calls:

    - (void) mergeToMainContext: (NSNotification*) saveNotification {
    
        [persistedMOC mergeChangesFromContextDidSaveNotification: saveNotification];
    
    }