문제

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];
도움이 되었습니까?

해결책

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__);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top