如何以编程方式编辑 plist?

How to edit a plist programmatically?

我有一个代码可以编辑 plist 文件。但是当代码运行时,它会更改 plist 文件,但会删除一些其他词典。你可以看看图片明白我的意思。

要查看编辑后的单词,请查看字典 "item 1" 和字符串 "name"。您会看到它需要从 "Second" 更改为 "newVALUE"。

原始plist是创建plist时的plist镜像。 然后你有 expected plist 这就是 plist 应该是什么样子的。 edited plist是应用代码后的plist。

这是代码:

NSString *plistPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
plistPath = [plistPath stringByAppendingPathComponent:@"PassaveData.plist"];

NSMutableArray*  newContent = [[NSMutableArray alloc]initWithContentsOfFile:plistPath];
NSMutableDictionary *Dict = [[NSMutableDictionary alloc]initWithDictionary:[newContent objectAtIndex:1]];
[Dict setValue:@"newVALUE" forKey:@"name"];
[Dict writeToFile:plistPath atomically:YES];

这些是图片

Click to see the images

您的原始 plist 包含一个字典数组。您创建一个新字典,然后仅用一个新字典覆盖原始的基于数组的 plist。

您需要用更新的字典更新加载的数组,然后写出整个更新的数组。

NSMutableArray *newContent = [[NSMutableArray alloc] initWithContentsOfFile:plistPath];
NSMutableDictionary *dict = [newContent[1] mutableCopy];
dict[@"name"] = @"newVALUE";
newContent[1] = dict;
[newContent writeToFile:plistPath atomically:YES];

注意数组和字典使用现代语法。