Question

I made dbfile sample.db by terminal in advance, and added the file to the project.
But the App create a dbfile from scratch, instead of refering to the db added.
How do I need to fix to refer the db added?

NSArray* paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES );
NSString* dir = [paths objectAtIndex:0];
FMDatabase* db = [FMDatabase databaseWithPath:[dir stringByAppendingPathComponent:samble.db]];
[db open];
Was it helpful?

Solution

Check for the existence of the database in Documents folder before you try to open it, and if it's not there, then copy the version from the bundle to the Documents folder before subsequently opening it from the Documents folder.

So, first, because you have your blank database sitting in the Documents folder, remove it (by uninstalling the app and then re-installing). And then you can do something like the following

BOOL success;
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* dir = [paths objectAtIndex:0];
NSString* documentsPath = [dir stringByAppendingPathComponent:@"samble.db"];
NSFileManager* fileManager = [NSFileManager defaultManager];

if (![fileManager fileExistsAtPath:documentsPath]) {
    NSString *bundlePath = [[NSBundle mainBundle] pathForResource:@"samble" ofType:@"db"];
    NSAssert(bundlePath, @"%s: database not found in bundle", __FUNCTION__);

    NSError *copyError;
    success = [fileManager copyItemAtPath:bundlePath toPath:documentsPath error:&copyError];
    NSAssert(success, @"%s: copyItemAtPath failed: %@", __FUNCTION__, copyError);
}

FMDatabase* db = [FMDatabase databaseWithPath:documentsPath];
NSAssert(db, @"%s: databaseWithPath failed", __FUNCTION__);
success = [db open];
NSAssert(success, @"%s: open failed", __FUNCTION__);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top