Last Updated: February 25, 2016
·
520
· e0d

Use pre-loaded CoreData file

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
    if (_persistentStoreCoordinator != nil)
    {
        return _persistentStoreCoordinator;
    }

    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"newCoreDataFile.sqlite
"];

    NSError *error = nil;



    if (![[NSFileManager defaultManager] fileExistsAtPath:[[[self applicationDocumentsDirectory] path]
                                                           stringByAppendingPathComponent: @"newCoreDataFile.sqlite
"]]){
        //database not detected
        NSLog(@"database not detected");
        NSURL  * defaultDatabase = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"sourceCoreDataFile" ofType:@"sqlite"]];
        NSError * error;
        if (![[NSFileManager defaultManager] copyItemAtURL:defaultDatabase toURL:storeURL error:&error]){
            // Handle Error somehow!
            NSLog(@"copy file error, %@", [error description]);
        }
    }

    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error])
    {

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

    return _persistentStoreCoordinator;
}