如何将应用程序包中的数据库文件放入 Library/Application support/ 目录?

How to put DB file from application's bundle in the Library/Application support/ directory?

我正在用 sqlite3 开发一个 OS X 应用程序,我想将数据库从应用程序的包复制到 Library/Application support/ 目录,因为我需要 read/write 但是,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
    }
}

这样的文件属于 LibraryApplication Support 文件夹。因此,使用 NSApplicationSupportDirectory 而不是 NSDocumentDirectory。此外,正如 File System Basics 文档所说,"All content in this directory should be placed in a custom subdirectory whose name is that of your app’s bundle identifier or your company."

例如:

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

对了,创建这个文件的时候,记得创建文件夹:

- (void)openDB {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *destinationPath = [self filePath];

    if (![fileManager fileExistsAtPath:destinationPath]) {
        NSError *error;
        if (![fileManager createDirectoryAtPath:[destinationPath stringByDeletingLastPathComponent] withIntermediateDirectories:TRUE attributes:nil error:&error]) {
            NSLog(@"%s: createDirectoryAtPath error: %@", __FUNCTION__, error);
        }

        NSString *sourcePath = [[NSBundle mainBundle] pathForResource:@"myDB" ofType:@"sql"];
        if (![fileManager copyItemAtPath:sourcePath toPath:destinationPath error:&error]) {
            NSLog(@"%s: copyItemAtPath error: %@", __FUNCTION__, error);
        }
    }
}