iOS – 使用文本文件捆绑应用程序

我有一个.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];

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...