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

Lou*_*uis 5 sqlite iphone xcode objective-c

将其作为资源添加后,数据库文件本身位于项目根目录中.

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

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

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

谢谢你的任何想法.

Mat*_*uch 9

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

NSString *path = [[NSBundle mainBundle] pathForResource:@"yourDb" ofType:@"sqlite"];
Run Code Online (Sandbox Code Playgroud)

但是您无法更改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);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 您无法更改捆绑包中的任何内容,因此您可以将在xcode中添加的所有文件视为只读.并且数据库将保留在库目录中,直到用户删除您的应用程序.它也将被itunes包含在备份中.因此,如果用户切换到新设备并从备份中恢复,则数据库将存在. (2认同)