Lou*_*uis 5 sqlite iphone xcode objective-c
将其作为资源添加后,数据库文件本身位于项目根目录中.
我只能通过指定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"];
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)
| 归档时间: |
|
| 查看次数: |
11690 次 |
| 最近记录: |