Damian Van de Kauter Damian Van de Kauter - 4 months ago 22
Objective-C Question

How to edit a plist programmatically?

I have a code to edit a plist file. But when the code runs, it changes the plist file but it deletes some other dictionaries. You can look at the images to see what I mean.

To see the edited word, look at dictionary "item 1" and at string "name". You will see that it needs to change from "Second" to "newVALUE".

The original plist is the image of the plist when the plist was created.
Then you have the expected plist which is what the plist should look like. And the edited plist is the plist after the code was applied.

This is the code:

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];

These are the images

Click to see the images


Your original plist contains an array of dictionaries. You create a new dictionary and then overwrite the original array-based plist with just the one new dictionary.

You need to update loaded array with the updated dictionary and then write out the whole updated array.

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

Note the use of modern syntax for the array and dictionary.