xcode 我应该如何在 iPhone 项目中指定 sqlite db 的路径?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5042836/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How should I specify the path for an sqlite db in an iPhone project?
提问by Louis Waweru
After adding it as a resource, the database file itself is in the project root.
将其添加为资源后,数据库文件本身就在项目根目录中。
I've only been able to open it by specifying the full path as OS X sees it, i.e., "/Users/Louis/Documents/Test Project/test.db".
我只能通过指定 OS X 看到的完整路径来打开它,即“/Users/Louis/Documents/Test Project/test.db”。
But of course there is no such path on an iPhone.
但是当然 iPhone 上没有这样的路径。
I think I should define the path as "application root/test.db" but I don't know how, or if that would even work anywhere else besides my development machine.
我想我应该将路径定义为“application root/test.db”,但我不知道如何,或者除了我的开发机器之外,它是否甚至可以在其他任何地方工作。
Thanks for any ideas.
感谢您的任何想法。
回答by Matthias Bauch
To get the path of the file you've added in XCode you would use pathForResource:ofType: with your mainBundle.
要获取您在 XCode 中添加的文件的路径,您可以将 pathForResource:ofType: 与您的 mainBundle 一起使用。
NSString *path = [[NSBundle mainBundle] pathForResource:@"yourDb" ofType:@"sqlite"];
But you can't change files in the mainBundle. So you have to copy it to another location. For example to the library of your app.
但是您不能更改 mainBundle 中的文件。所以你必须将它复制到另一个位置。例如到您的应用程序库。
You could do it like this:
你可以这样做:
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);
}
}
回答by Josh
Don't just use the SQLite API, use this amazing wrapper called FMDB: https://github.com/ccgus/fmdb
不要只使用 SQLite API,使用这个名为 FMDB 的神奇包装器:https: //github.com/ccgus/fmdb