【问题标题】:How to put DB file from application's bundle in the Library/Application support/ directory?如何将应用程序包中的数据库文件放在 Library/Application support/ 目录中?
【发布时间】:2015-03-23 01:11:18
【问题描述】:

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

【问题讨论】:

  • 你想要什么,有什么问题?
  • 您的问题是关于“应用程序数据所在的位置”还是更多关于“使用初始固定装置填充数据库”或完全其他的问题?
  • 假设这不是用户文件,而是应用程序使用的数据库,您可能会将其存储在 Application Support 文件夹中,如 The库目录存储File System Basics 的应用程序特定文件 部分。如果这是一个用户文件,你会提示用户他们想把它放在哪里。如果它是一个临时文件,你会使用临时文件夹。
  • @Rob 是的,这是应用程序使用的数据库,我想将其存储在 Application Support 文件夹中。
  • @Zaph 如何将数据库文件从应用程序包复制到应用程序支持文件夹?

标签: database sqlite osx-yosemite nsfilemanager


【解决方案1】:

这样的文件属于LibraryApplication Support 文件夹。所以,不要使用NSDocumentDirectory,而是使用NSApplicationSupportDirectory。此外,正如 File System Basics 文档所述,“此目录中的所有内容都应放在一个自定义子目录中,其名称为您的应用程序包标识符或您的公司名称。”

例如:

- (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);
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-21
    • 1970-01-01
    • 1970-01-01
    • 2016-08-07
    • 2011-08-25
    • 1970-01-01
    • 2016-01-14
    相关资源
    最近更新 更多