我事先通过终端制作了dbfile sample.db
,并将该文件添加到项目中
但是应用程序从头开始创建一个dbfile,而不是引用添加的数据库
我如何修复以引用db添加?
NSArray* paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES );
NSString* dir = [paths objectAtIndex:0];
FMDatabase* db = [FMDatabase databaseWithPath:[dir stringByAppendingPathComponent:samble.db]];
[db open];
答案 0 :(得分:0)
在尝试打开之前检查Documents文件夹中是否存在数据库,如果不存在,则将该版本从软件包复制到Documents文件夹,然后再从Documents文件夹中打开它。
首先,因为您将空白数据库放在Documents文件夹中,将其删除(通过卸载应用程序然后重新安装)。然后你可以做类似下面的事情
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:©Error];
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__);