iOS - 保存为plist

时间:2012-09-11 08:24:55

标签: iphone ios plist

我正在尝试更改plist的值(@key“userId”,其起始值为0)

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

1 个答案:

答案 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); 
}