2012-11-19 28 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

對不起,我誤解了你的問題,我正在更新我的答案 –

相關問題