我应该如何在iPhone项目中指定sqlite数据库的路径? [英] How should I specify the path for an sqlite db in an iPhone project?
问题描述
将其作为资源添加后,数据库文件本身就位于项目根目录中。
After adding it as a resource, the database file itself is in the project root.
我只能通过指定完整路径来打开它OS X看到它,即/ Users / Louis / Documents / Test Project / test.db。
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".
但当然iPhone上没有这样的路径。
But of course there is no such path on an iPhone.
我认为我应该将路径定义为application root / test.db,但我不知道如何,或者除了我的开发之外还能在其他地方工作机器。
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.
感谢您的任何想法。
推荐答案
要获得您在XCode中添加的文件的路径,您将使用pathForResource:ofType:与您的mainBundle。
To get the path of the file you've added in XCode you would use pathForResource:ofType: with your mainBundle.
NSString *path = [[NSBundle mainBundle] pathForResource:@"yourDb" ofType:@"sqlite"];
但是你无法更改mainBundle中的文件。所以你必须将它复制到另一个位置。例如,您的应用程序库。
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.
你可以这样做:
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);
}
}
这篇关于我应该如何在iPhone项目中指定sqlite数据库的路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!