如何将应用程序包中的DB文件放在库/应用程序支持/目录中?

时间:2015-01-23 21:54:48

标签: database sqlite osx-yosemite nsfilemanager

我正在开发一个带有sqlite3的OS X应用程序,我想将数据库从应用程序的bundle复制到Library / Application support /目录,因为我需要在db上读/写,但是,sql被复制到我的文档中文件夹,我不想要那个位置。我的代码:

- (NSString *)filePath {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    return [[paths objectAtIndex:0] stringByAppendingPathComponent:@"myDB.sql"];
}

- (void)openDB {
    NSString *destinationPath = [self filePath];
    if (![[NSFileManager defaultManager] fileExistsAtPath:destinationPath]) {
    NSString *sourcePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"myDB.sql"];
    NSError *error;
    [[NSFileManager defaultManager] copyItemAtPath:sourcePath toPath:destinationPath error:&error];
    if (error != nil) {
        //Error
    }
}

1 个答案:

答案 0 :(得分:1)

此类文件属于Application Support的{​​{1}}文件夹。因此,请使用Library而不是NSDocumentDirectory。此外,正如File System Basics文档所述,"此目录中的所有内容都应放在一个自定义子目录中,该子目录的名称是应用程序包标识符或公司的名称。"

例如:

NSApplicationSupportDirectory

顺便说一句,在创建此文件时,请记住创建文件夹:

- (NSString *)filePath {
    NSString *applicationSupport = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES)[0];
    NSString *applicationFolder = [applicationSupport stringByAppendingPathComponent:[[NSBundle mainBundle] bundleIdentifier]];
    return [applicationFolder stringByAppendingPathComponent:@"myDB.sql"];
}