How to use Core Data with multiple Store Files

- by

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:



If you enjoy my content, please consider supporting me on Ko-fi. In return you can browse this whole site without any pesky ads! More details here.

Leave a Comment!

This site uses Akismet to reduce spam. Learn how your comment data is processed.