2012-11-19 29 views
4

我有一个.json文件,我想与我的应用程序捆绑为一个资源。我读过File System Programming Guide其中说你应该把支持文件放在<Application_Home>/Library/Application Support。那么在构建我的应用程序之前,如何将我的.json文件放入此目录中?iOS - 与文本文件捆绑应用程序

如何在运行时引用文件?

+0

这是否意味着在运行时是只读文件,还是需要更新文件? – rmaddy

+0

我会偶尔需要更新文件(每年一次左右)。 –

+0

更新是在运行时或者作为应用更新的一部分在应用中完成的? – rmaddy

回答

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]; 
+0

因此只能在运行时写入应用程序支持目录? –

+0

是的。应用程序沙箱不会创建,直到该应用程序安装在用户的设备上。您只能在应用构建时将文件放入包中。 – rmaddy

+0

谢谢@rmaddy - 这个解决方案对我来说非常合适。 – cnp

0

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

需要的目录在运行时创建,文件从主束搬到那里,那么你可以使用在链接中描述的方法来访问它们。

+0

我指的是具有关于iOS应用程序(不仅仅是MacOS)的信息的文件系统编程指南。最明确的是iOS应用程序的文件系统(您可以在指南中阅读)。 –

+0

对不起,我误解了你的问题,我正在更新我的答案 –

相关问题