0

我正在尝试更改 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

4

1 回答 1

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); 
}
于 2012-09-11T08:45:43.000 回答