我有一个.json文件,我希望将其作为资源与我的应用程序捆绑在一起.我已经阅读了文件系统编程指南,它说你应该把支持文件放在<Application_Home>/Library/Application Support
.那么在构建我的应用程序之前如何将我的.json文件放在这个目录中呢?
如何在运行时引用该文件?
如果您的文件始终是只读的(仅作为应用更新的一部分更新),则将该文件添加到项目中应用的资源中.然后你只需从应用程序包中读取文件:
// assume a filename of file.txt. Update as needed
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"file" ofType:@"txt"];
Run Code Online (Sandbox Code Playgroud)
如果您需要在应用程序中提供初始文件但在运行时进行更新,则需要像上面那样打包文件,但是第一次运行应用程序时,您需要将文件复制到应用程序沙箱中的另一个可写位置.
// 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];
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2154 次 |
最近记录: |