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

我有一个.json文件,我想要作为资源与我的应用程序捆绑在一起。 我已经阅读了文件系统编程指南 ,它指出你应该把支持文件放在<Application_Home>/Library/Application Support 。 那么在构build我的应用程序之前,如何将我的.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]; 

一个很好的解释在这里http://www.cocoawithlove.com/2010/05/finding-or-creating-application-support.html

该目录需要在运行时创build,文件从主包中移出,然后可以使用链接中描述的方法访问它们。