2012-09-11 66 views
0

我試圖改變一個plist中的值(@key「用戶id」,它具有爲0的初始值)的iOS - 保存到一個plist中

NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"GlobalSettings" ofType:@"plist"]; 
NSMutableDictionary *data = [NSMutableDictionary dictionaryWithContentsOfFile:plistPath]; 
NSDictionary *userId = [data objectForKey:@"userId"]; 

[data setValue:(@"99") forKey:@"userId"]; 
[data writeToFile:plistPath atomically: NO]; 

userId = [data objectForKey:@"userId"]; 
NSLog(@"%@", userId); 

日誌顯示該值已更改爲99 ,但是當我打開plist中值仍爲0

回答

4

您不能保存在應用程序的主包數據,而不是你在文檔目錄中這樣做:

NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES); 
NSString *documentsDirectory = [paths objectAtIndex:0]; 
NSString *plistFilePath = [documentsDirectory stringByAppendingPathComponent:@"GlobalSettings.plist"]; 

if([[NSFileManager defaultManager] fileExistsAtPAth:plistFilePath]) 
{//already exits 

    NSMutableDictionary *data = [NSMutableDictionary dictionaryWithContentsOfFile:plistFilePath]; 
    NSDictionary *userId = [data objectForKey:@"userId"]; 
    [data setValue:(@"99") forKey:@"userId"]; //new value here 
    [data writeToFile:plistPath atomically: YES]; 
    userId = [data objectForKey:@"userId"]; 
    NSLog(@"%@", userId); 
} 
else{ //firstly take content from plist and then write file document directory 

NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"GlobalSettings" ofType:@"plist"]; 
NSMutableDictionary *data = [NSMutableDictionary dictionaryWithContentsOfFile:plistPath]; 
NSDictionary *userId = [data objectForKey:@"userId"]; 

[data setValue:(@"99") forKey:@"userId"];//new value here 
[data writeToFile:plistFilePath atomically:YES]; 

userId = [data objectForKey:@"userId"]; 
NSLog(@"%@", userId); 
} 
+0

謝謝。從那時起,我如何引用文檔目錄中的plist? –

+0

檢查我的答案,它應該清除所有你的疑惑,只是得到你的文件的路徑,並創建nsdictionary dictionaryWithContentsOfFile:yourFilePath –

+0

偉大的,謝謝! –