How to use a provided store file with Core Data

Apple’s recommended method for dealing with “bring your own store files” for Core Data is to copy the store file into your app’s Documents directory, where it can be accessed for read and write queries.

However, if you don’t need to write to your store file, then you can also add a provided store file inside the main bundle. It would save some space on the user’s device.

Here’s the custom initialiser for NSPersistentStoreCoordinator, tweaked to show how to handle this:

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }
    
    NSURL *providedStore = [[NSBundle mainBundle] URLForResource:@"YourStorefile" withExtension:@"sqlstore"];
    NSFileManager *manager = [NSFileManager defaultManager];
    
    // if we don't have a file in our bundle, freak out at once!
    if (![manager fileExistsAtPath:[providedStore path]]) {
        NSLog(@"Houston, we have a problem: The provided store file doesn't exist in our bundle :-(");
        abort();
    }
    
    NSError *error = nil;
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    
    // the options is nil by default
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:providedStore options:@{NSReadOnlyPersistentStoreOption:@YES} error:&error]) {

        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }
    
    return _persistentStoreCoordinator;
}

Note that the option NSReadOnlyPersistentStoreOption:@YES is not strictly necessary.





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.