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

时间:2011-02-18 15:00:48

标签: iphone objective-c xcode sqlite

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

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

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

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

感谢任何想法。

3 个答案:

答案 0 :(得分:9)

要获取您在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);
    }
}

答案 1 :(得分:2)

不要只使用SQLite API,使用这个名为FMDB的惊人包装器:https://github.com/ccgus/fmdb

答案 2 :(得分:1)

相关问题