2012-07-19 157 views
0

我正在開發一個包含5個plist文件的應用程序。我想將所有這些文件保存在文檔目錄中。因爲我想動態地向它們添加數據。我從plist在文檔目錄中創建多個Plist文件..?

NSMutableArray *pathsArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *docpath = [pathsArray objectAtIndex:0]; 
NSString *scorePlistPath = [docpath stringByAppendingPathComponent:@"highScores.plist"]; 

if (![[NSFileManager defaultManager] fileExistsAtPath:scorePlistPath]) { 
    scorePlistPath = [[NSBundle mainBundle] pathForResource:@"highScores" ofType:@"plist"]; 
} 
highScoreArray = [[NSMutableArray alloc]initWithContentsOfFile:scorePlistPath]; 

寫入數據創建對plist

scorePlistPath = [docpath stringByAppendingPathComponent:@"highScores.plist"]; 

[highScoreArray writeToFile:scorePlistPath atomically:YES]; 

使用

檢索數據的plist路徑現在我想補充一個plists在文件目錄..不要在包。我怎樣才能做到這一點..?

回答

0

編程您不能文件添加到應用程序包,因爲您沒有權限,並保存或加載文件從Documents文件夾是不是一個大問題:

首先,你需要定義網址該文件是:

NSString *_filename = @"myOwn.plist"; 
NSURL *_resourceURL = [[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject] URLByAppendingPathComponent:_fileName]; 

那麼你可以保存文件

NSArray *_array = // your array as you defined 
[_array writeToURL:_resourceURL atomically:true]; 

,隨時隨地的文件可以被再次加載

NSData *_plistData = [NSData dataWithContentsOfFile:[_resourceURL path]]; 
NSArray *_loadedArray = [NSPropertyListSerialization propertyListFromData:_plistData mutabilityOption:NSPropertyListImmutable format:nil errorDescription:nil]; // the option or the format parameter might be set for your special wishes, so check the documentation, please 

中提琴,它完成。

UPDATE#1

此代碼任何真實設備上完美的工作與iOS4.3+,它從未被在模擬器上進行測試。

+0

爲您的代碼'Plist'文件不在文檔目錄顯示但我見'plist'文件上面給出的代碼文件目錄中完美呈現......還有一兩件事是我要保存5個不同文檔目錄中的plist文件。但是你的代碼也在控制檯中顯示相同的路徑。 – SriKanth 2012-07-19 12:39:27

+0

我已經複製從我住的應用程序的代碼片段,它可在AppStore現在,它正在完美地的iOS4.3 +每個設備上,也許你已經實現其中的某部分錯誤,因爲它節省了'NSArray的'放入'Documents'文件夾並從那裏讀回來。 :)請複製並粘貼你如何實現它。如果你想保存5個plist文件,你應該爲5個文件創建5個不同的'_rescourceURL',你不覺得嗎?它們中的一種方法只能保存一個文件。 :) – holex 2012-07-19 12:45:47

+0

是的,這是你寫的加載方法。它有什麼問題?這並不是將任何文件保存到'Documents'文件夾,而是將它們讀回到內存中,正如我在答案中所寫的那樣。 – holex 2012-07-19 12:56:48