2010-01-19 172 views
1
NSString *myfile = [[NSBundle] mainBundle] pathForResource:@"fileName" ofType:@"plist"];  
NSMutableArray *mydata= [[NSMutableArray alloc] initWithContentsOfFile:myfile]; 

/* code to modify mydata */ 

[mydata writeToFile:myfile atomically:YES] 

如果模擬器'fileName.plist'被修改,但在iPhone設備文件保持不變的情況下。也沒有例外。writeToFile在iphone上失敗,但在模擬器上工作

上述代碼是否可以在iPhone和模擬器上正常工作?

另外在調試器中,當我將鼠標懸停在'mydata'上時,在仿真器和設備的情況下可以看到不同的值。在模擬器的情況下,我會看到例如'5個對象',但在實際設備的情況下,它會顯示'{(int)[$VAR count]}'。這可能與文件沒有被寫入有關嗎?

回答

5

您無法寫入捆綁軟件資源目錄中的文件。最重要的是,你不想這樣做,因爲更新應用程序時,任何更改都會被覆蓋。文檔目錄在各個版本中保持不變,並且(我相信)它通過iTunes進行備份。

這是一個代碼片段,用於檢查plist的文檔目錄。如果該文件不存在,則將資源複製到文檔目錄中。

BOOL success; 
NSFileManager* fileManager = [NSFileManager defaultManager]; 
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *documentsDirectory = [paths objectAtIndex:0]; 
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"score.plist"]; 
success = [fileManager fileExistsAtPath:writableDBPath]; 
if (success) return success; 
// The writable database does not exist, so copy the default to the appropriate location. 
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"score.plist"]]; 
success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error]; 
return success; 
+0

謝謝肯尼。這很有幫助。我已經使用這個代碼實現了我的東西,現在它也和設備一起工作。 – climbon 2010-01-20 07:11:46

+0

謝謝,做到了。用我的高分(比如這個例子)來解決這個問題,並且從一個包資源中複製它是包含一些默認分數的好主意。 – 2013-06-07 15:24:07

相關問題