在applicationdidfinishlaunch期间将DB从bundle复制到Documents目录

时间:2013-03-17 07:21:28

标签: ios objective-c

当我的应用程序启动时,我会检查Documents目录中是否存在数据库。如果没有,那么我想将主捆绑中的数据库复制到应用程序的Documents目录中。

看起来很简单,但是当我在模拟器中运行代码时,我只得到一个可可错误代码4。可可错误代码表示文件不存在。我把它缩小到很可能是因为代码中此时文档目录不存在。

这是我的代码:

NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *appDBPath = [documentsDirectory stringByAppendingPathComponent:@"app.db"];

if([[NSFileManager defaultManager] fileExistsAtPath:appDBPath]) {
    //PERFORM DATA MIGRATIONS IF ANY EXIST
}
else {
    NSString *appDBBundlePath = [[NSBundle mainBundle] pathForResource:@"app" ofType:@"db"];
    NSError *error;
    if(![[NSFileManager defaultManager] copyItemAtPath:appDBBundlePath toPath:appDBPath error:&error]) {
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Error"
                                                        message:[error localizedDescription]
                                                       delegate:nil
                                              cancelButtonTitle:@"ok"
                                              otherButtonTitles:nil];
        [alert show];
    }
}

我一直认为一旦安装了应用程序,Documents目录就会存在。我究竟做错了什么?注意:我可以使用物理设备上的应用程序将数据库从bundle复制到Documents目录。

0 个答案:

没有答案