How should I specify the path for an sqlite db in an iPhone project?

前端 未结 3 1911
清歌不尽
清歌不尽 2020-12-11 06:31

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., \"

相关标签:
3条回答
  • 2020-12-11 07:11

    Getting Paths to Standard Application Directories

    0 讨论(0)
  • 2020-12-11 07:21

    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"];
    

    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.

    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);
        }
    }
    
    0 讨论(0)
  • 2020-12-11 07:27

    Don't just use the SQLite API, use this amazing wrapper called FMDB: https://github.com/ccgus/fmdb

    0 讨论(0)
提交回复
热议问题