加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

我应该如何在iPhone项目中指定sqlite数据库的路径?

发布时间:2020-12-15 01:47:36 所属栏目:百科 来源:网络整理
导读:将其作为资源添加后,数据库文件本身位于项目根目录中. 我只能通过指定OS X看到它的完整路径来打开它,即“/ Users / Louis / Documents / Test Project / test.db”. 但当然iPhone上没有这样的路径. 我想我应该将路径定义为“application root / test.db”,但
将其作为资源添加后,数据库文件本身位于项目根目录中.

我只能通过指定OS X看到它的完整路径来打开它,即“/ Users / Louis / Documents / Test Project / test.db”.

但当然iPhone上没有这样的路径.

我想我应该将路径定义为“application root / test.db”,但我不知道如何,或者除了我的开发机器之外还能在其他地方工作.

谢谢你的任何想法.

解决方法

要获取您在XCode中添加的文件的路径,您将使用pathForResource:ofType:与您的mainBundle.

NSString *path = [[NSBundle mainBundle] pathForResource:@"yourDb" ofType:@"sqlite"];

但是您无法更改mainBundle中的文件.所以你必须将它复制到另一个位置.例如,您的应用程序库.

你可以这样做:

NSString *libraryPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,NSUserDomainMask,YES) lastObject];
NSString *targetPath = [libraryPath stringByAppendingPathComponent:@"yourDB.sqlite"];

if (![[NSFileManager defaultManager] fileExistsAtPath:targetPath]) {
    // database doesn't exist in your library path... copy it from the bundle
    NSString *sourcePath = [[NSBundle mainBundle] pathForResource:@"yourDb" ofType:@"sqlite"];
    NSError *error = nil;

    if (![[NSFileManager defaultManager] copyItemAtPath:sourcePath toPath:targetPath error:&error]) {
        NSLog(@"Error: %@",error);
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读