4

我有一个 .json 文件,我想将它作为资源与我的应用程序捆绑在一起。我已经阅读了文件系统编程指南,它说您应该将支持文件放在<Application_Home>/Library/Application Support. 那么在构建我的应用程序之前,如何将我的 .json 文件放在这个目录中呢?

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

4

2 回答 2

5

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

// 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];
于 2012-11-19T23:37:14.243 回答
0

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

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

于 2012-11-19T21:09:08.517 回答