Alan
Alan

Reputation: 4325

Preloaded Core Data Database Not Working

I have created a core data database in one application which involved sucking out info from an API and populating a database.

I would now like to use it in another app.

I have copied the .xcdatamodeld file and NSManagedObject classes across.

I have added and imported Core Data framework.

I have copied the .sqlite file into my new application's resources as the default database.

I am using the following code which is supposed to copy out the default database to the Documents directory and open it so that I may perform queries on it.

It is causing the app to crash with no error message, any thoughts on where I'm going wrong?

If I was to create a database here using saveToURL, I know the filename would be persistentStore not Trailer.sqlite as per below, is that relevant?

Thanks

- (void)viewDidLoad
{
[super viewDidLoad];


// Get URL -> "<Documents Directory>/<TrailerDB>" 
NSURL *url = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];

url = [url URLByAppendingPathComponent:@"TrailerDB"];

UIManagedDocument *doc = [[UIManagedDocument alloc] initWithFileURL:url];

// Copy out default db to documents directory if it doesn't already exist
NSFileManager *fileManager = [NSFileManager defaultManager];

if (![fileManager fileExistsAtPath:[url path]]) {
    NSString *defaultDB = [[NSBundle mainBundle] 
                                  pathForResource:@"trailerdatabase" ofType:@"sqlite"];
    if (defaultDB) {

        [fileManager copyItemAtPath:defaultDB toPath:[url path] error:NULL];

    }
}

if (doc.documentState == UIDocumentStateClosed) {

    // exists on disk, but we need to open it
    [doc openWithCompletionHandler:^(BOOL success) 
     {

         if (success) [self useDatabase:doc];

         if (!success) NSLog(@"couldn’t open document at %@", url);


     }];

} else if (doc.documentState == UIDocumentStateNormal) 
{
    [self useDatabase:doc];
}

}

Upvotes: 0

Views: 798

Answers (1)

jackslash
jackslash

Reputation: 8570

Ive had another look and I'm not sure what you're doing but this code below is what i do that would answer your question. I check to see if the working database exists and if it doesn't i move it in place from the application bundle and then proceed to load it. I have left the stock comments from the Apple template in as i think they may end up being helpful.

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

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

    NSError *error = nil;

    if (![[NSFileManager defaultManager] fileExistsAtPath:[[self applicationDocumentsDirectoryString] stringByAppendingPathComponent: @"workingDataBase.sqlite"]]){
        //database not detected
        NSLog(@"database not detected");
        NSURL  * defaultDatabase = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"DefaultData" 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])
    {
        /*
         Replace this implementation with code to handle the error appropriately.

         abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.

         Typical reasons for an error here include:
         * The persistent store is not accessible;
         * The schema for the persistent store is incompatible with current managed object model.
         Check the error message to determine what the actual problem was.


         If the persistent store is not accessible, there is typically something wrong with the file path. Often, a file URL is pointing into the application's resources directory instead of a writeable directory.

         If you encounter schema incompatibility errors during development, you can reduce their frequency by:
         * Simply deleting the existing store:
         [[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil]

         * Performing automatic lightweight migration by passing the following dictionary as the options parameter: 
         [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption, [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];

         Lightweight migration will only work for a limited set of schema changes; consult "Core Data Model Versioning and Data Migration Programming Guide" for details.

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

    return __persistentStoreCoordinator;
}

Upvotes: 1

Related Questions