gpt4 book ai didi

iOS - 将应用程序与文本文件捆绑在一起

转载 作者:可可西里 更新时间:2023-11-01 05:37:25 25 4
gpt4 key购买 nike

我有一个 .json 文件,我想将其作为资源与我的应用程序捆绑在一起。我读过 File System Programming Guide这表示您应该将支持文件放在 <Application_Home>/Library/Application Support 中.那么如何在构建我的应用程序之前将我的 .json 文件放在这个目录中呢?

我如何在运行时引用该文件?

最佳答案

如果您的文件将始终为只读(仅作为应用更新的一部分进行更新),则将该文件添加到项目中应用的资源中。然后你只需从应用程序的包中读取文件:

// assume a filename of file.txt. Update as needed
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"file" ofType:@"txt"];

如果您需要为您的应用程序提供一个初始文件但在运行时进行更新,那么您需要像上面那样打包该文件,但是您的应用程序第一次运行时您需要将文件复制到您的另一个可写位置应用的沙箱。

// Get the Application Support directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
NSString *appSupportDirectory = [paths objectAtIndex:0];

// Create this path in the app sandbox (it doesn't exist by default)
NSFileManager *fileManager = [NSFileManager defaultManager];
[fileManager createDirectoryAtPath:appSupportDirectory withIntermediateDirectories:YES attributes:nil error:nil];

// Copy the file from the app bundle to the application support directory
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"file" ofType:@"txt"];
NSString *newPath = [appSupportDirectory stringByAppendingPathComponent:[filePath lastPathComponent]];
[fileManager copyItemAtPath:filePath toPath:newPath error:nil];

关于iOS - 将应用程序与文本文件捆绑在一起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13462243/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com