2013-06-03 41 views
0

我有一個問題,我創建了電影的plist。 根的類型是字典 和皮克斯型陣列 3串電影片名 我能夠從列表下面的代碼從這裏閱讀沒有問題寫給mainBundle plist

NSString *path = [[NSBundle mainBundle] pathForResource:@"Movies" ofType:@"plist"]; 

NSMutableDictionary *movies =[[NSMutableDictionary alloc] initWithContentsOfFile:path]; 

我可以打印列表中沒有任何問題的。 我想現在再添加一部電影到這個列表中。 所以我將列表轉移到一個數組,然後將數組保存迴文件,但它不工作。 任何想法我錯了哪裏?

NSMutableArray *array= [movies valueForKey:@"Pixar"]; 
NSString *[email protected]"Incredibles"; 
[array addObject:incredible]; 

[movies setObject:array forKey:@"Pixar"]; 

[movies writeToFile:path atomically:YES]; 
+3

當你沒有搜索該你出了問題。重複**很多次** – 2013-06-03 21:05:31

+0

我一直在尋找一點現在,如果你看到它,請給我鏈接,而不是隻是說重複 – ifrapps

+1

[修改plist可能的重複不工作](http:// stackoverflow.com/questions/6368752/modifying-a-plist-is-not-working)**和** [如何更新ios中的plist文件](http://stackoverflow.com/questions/16870092/how-to -update-the-plist-file-in-ios)**和** [iphone寫入文件失敗](http://stackoverflow.com/questions/3386973/iphone-write-to-file-fails) - 搜索有什麼困難? – 2013-06-03 21:08:04

回答

3

您不能在設備上寫入捆綁包。模擬器不強制執行這些限制,但設備會執行這些限制。

一種方法是:

  1. 查看是否在文件中Documents文件夾中存在。

  2. 如果是這樣,請從Documents文件夾中讀取。如果沒有,請從捆綁中讀取它。

  3. 完成添加/刪除記錄後,將文件寫入Documents文件夾。

這樣:

NSString *bundlePath = [[NSBundle mainBundle] pathForResource:@"Movies" ofType:@"plist"]; 
NSString *docsFolder = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0]; 
NSString *documentsPath = [docsFolder stringByAppendingPathComponent:@"Movies.plist"]; 

NSMutableDictionary *movies = nil; 

if ([[NSFileManager defaultManager] fileExistsAtPath:documentsPath]) 
    movies = [NSMutableDictionary dictionaryWithContentsOfFile:documentsPath]; 

if (!movies) 
    movies = [NSMutableDictionary dictionaryWithContentsOfFile:bundlePath]; 

// do whatever edits you want 

[movies writeToFile:documentsPath atomically:YES];