Search code examples
iosmultithreadingcore-datansmanagedobjectcontext

Core Data Setting Up Multiple managedObjectContexts


In an app that I am working on I need to access and write to Core Data at the same time. I have been able to gather that this means that I need to user multiple managedObjectContexts but I don't understand how I am supposed to setup those two managedObjectContexts.

I understand that once I have them setup I need to do the write operations on a background thread on its managedObjectContext and then merge the data through an operation like this: Core Data and threads / Grand Central Dispatch .

So my question is, how would I go about initiating two separate managedObjectContexts so that I can then use them as described?


Solution

  • You have to create two separate NSManagedObjectContexts with the same NSPersistentStoreCoordinator like this,

    First create two NSManagedObjectContexts name as backgroundManagedObjectContext and mainBackgroundManagedObjectContext in your model class like this

    + (NSManagedObjectContext *)backgroundManagedObjectContext
        {
            static NSManagedObjectContext * backgroundManagedObjectContext;
            if(backgroundManagedObjectContext != nil){
                return backgroundManagedObjectContext;
            }
            @try {
                NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
                if (coordinator != nil) {
                    backgroundManagedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
                    [backgroundManagedObjectContext setPersistentStoreCoordinator: [self persistentStoreCOordinator]];
                }
            }
            @catch (NSException *exception) {
                NSLog(@"Exception occur %@",exception);
            }
            return backgroundManagedObjectContext;
    
        }
    

    then both will need get the same persistentStoreCoordinator then need to merge your backgroungManagedObjectContext to mainBackgroundManagedObjectContext, for that create NSNotification whenever you save the data into backgroundManageObjectContext like this

    [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(contextDidSave:)
                                                     name:NSManagedObjectContextDidSaveNotification
                                                   object:nil];
    

    then you have to implement this notification method for updating your mainManagedObjectContext like this

    - (void)contextDidSave:(NSNotification *)notification
        {
            SEL selector = @selector(mergeChangesFromContextDidSaveNotification:);
            [[self mainManagedObjectContext] performSelectorOnMainThread:selector withObject:notification waitUntilDone:YES];
    
        }