objective-c - 创建数据库文件(如果不存在)

标签 objective-c ios sqlite fmdb

我正在尝试在第一个应用程序的启动中创建数据库文件。使用的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/

相关文章:

join - SQLite选择不同的联接查询如何

javascript - 如何将一个数据字段的值复制到同一 SQLite 数据库中的另一个表

php - 使用 PHP 的大量 SQLite 插入

ios - 如何从 Swift 3 中的数据中提取 Int16

ios - 点击单元格时更改表格单元格内 UILabel 的颜色

objective-c - Objective-C/中 drain、release、dealloc 和 retain 之间的区别

html - Kendo UI 移动和 MySQL 数据库连接

c# - 使用自定义单元配件的 Monotouch - 如何判断选择了哪一行

iOS AWSCognito 2.4.X AWSIdentityProviderManager 数字示例

ios - 如何在 NSMutableAttributedString 中传递两个字符串