How to use a provided store file with Core Data

- by

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.

Add your voice!

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