我正在尝试在第一个应用程序的启动中创建数据库文件。使用的FMDB库。为此,我正在检查数据库文件是否已经存在,如果不存在,我想从项目中复制数据库文件。
我的代码:
-(void)checkAndCreateDatabase {
NSLog(@"check and create database doing");
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *dbFileName = [docDir stringByAppendingPathComponent:@"FriendsDatabase.sqlite3"];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
if (![fileManager fileExistsAtPath:dbFileName]) {
[fileManager copyItemAtPath:[[NSBundle mainBundle] pathForResource:@"FriendsDatabase" ofType:@"sqlite3"] toPath:dbFileName error:&error];
NSLog(@"database created");
} else {
NSLog(@"fail to create database");
}
FMDatabase *_db = [[FMDatabase alloc] initWithPath: dbFileName];
if (![_db open]) {
[_db release];
NSLog(@"Could't open DB");
}
_db.logsErrors = NO;
self.db = _db;
[_db release];
}
但是我有一个错误:
'NSInvalidArgumentException', reason: '*** -[NSFileManager copyItemAtPath:toPath:error:]: source path is nil'
。我做错了什么?
最佳答案
您的主捆绑包中似乎没有名为“FriendsDatabase.sqlite3”的文件。 (如果有一个,则对-copyItemAtPath:toPath:error:
的调用中的源路径不会为零。)
尝试将代码更改为如下所示:
NSString *path = [[NSBundle mainBundle] pathForResource:@"FriendsDatabase" ofType:@"sqlite3"];
[fileManager copyItemAtPath:path toPath:dbFileName error:&error];
然后使用调试器逐步检查代码,并检查
path
的值。请注意,您已在代码中指定“FriendsDatabase”(注意为“s”)作为文件名,但是注释将文件称为“FriendDatabase”。也许您只是在代码中拼写了错误的文件名-这是使用常量的一个很好的理由!
关于objective-c - 创建数据库文件(如果不存在),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10710280/