How to use Core Data with multiple Store Files

Sometimes it can be useful to split your Core Data Store File across multiple files. For example, one file could live on the local file system, while the other could live in iCloud.

We can do this by telling the Xcode Model Editor to add more than one Configuration, each of which can be allocated certain Entities. Each Configuration can be configured to use a separate store file.

Consider this example code which is provided by the Xcode 4.6 templates to initiate the Persistent Store Coordinator:

    // Single Store - original code provided with template
    NSURL *url = [applicationFilesDirectory URLByAppendingPathComponent:@"Two_Stores.storedata"];
    NSPersistentStoreCoordinator *coordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:mom];
    if (![coordinator addPersistentStoreWithType:NSXMLStoreType configuration:nil URL:url options:nil error:&error]) {
        [[NSApplication sharedApplication] presentError:error];
        return nil;
    }

Notice the absence of a Configuration in the addPersistentStoreWithType method. You can create Configurations by click-holding the big PLUS button that let’s you add Entities by default. GIve them a meaningful name, then drag-and-drop in your Entities:

Two Stores Model Editor

Next you’ll replace the code above with something like this, adding more than one store file to your Persistent Store Coordinator:

    // create URLs for each store
    NSURL *url1 = [applicationFilesDirectory URLByAppendingPathComponent:@"Store-One.xml"];
    NSURL *url2 = [applicationFilesDirectory URLByAppendingPathComponent:@"Store-Two.xml"];
    
    // create the coordinator
    NSPersistentStoreCoordinator *coordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:mom];
    
    // add store files to coordinator
    if (![coordinator addPersistentStoreWithType:NSXMLStoreType configuration:@"Configuration1" URL:url1 options:nil error:&error]) {
        [[NSApplication sharedApplication] presentError:error];
        return nil;
    }
    
    if (![coordinator addPersistentStoreWithType:NSXMLStoreType configuration:@"Configuration2" URL:url2 options:nil error:&error]) {
        [[NSApplication sharedApplication] presentError:error];
        return nil;
    }

Now you’ll work with two store files in the same Managed Object Context. This also means that whatever operation you call on the context (save for example) will be executed on both store files.

Demo Project

I’ve added a Demo Project to GitHub which demonstrates this in Mac OS X:





Jay is the CEO and founder of WP Hosting, a boutique style managed WordPress hosting and support service. He has been working with Plesk since version 9 and is a qualified Parallels Automation Professional. In his spare time he likes to develop iOS apps and WordPress plugins, or draw on tablet devices. He blogs about his coding journey at http://wpguru.co.uk and http://pinkstone.co.uk.