Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a new dictionary to my plist file

Root ---- Array
  Item 0- Dictionary
    fullName ---- String
    address ---- String
  Item 1 ---- Dictionary
    fullName ---- String
    address ---- String

I have a plist that looks like the one about. In a View I have a button that when clicked I'd like to add a new "Item 2" or 3 or 4 or 5 etc... I just want to add a few more names and addresses.

I've spent 3 hours tonight searching for the perfect example but came up short. The Apple property lists samples were way too deep. I've seen code that probably will come close.

Thanks So Much

NSMutableDictionary *nameDictionary = [NSMutableDictionary dictionary]; [nameDictionary setValue:@"John Doe" forKey:@"fullName"]; [nameDictionary setValue:@"555 W 1st St" forKey:@"address"];

NSMutableArray *plist = [NSMutableArray arrayWithContentsOfFile:[self dataFilePath]];
[plist addObject:nameDictionary];
[plist writeToFile:[self dataFilePath] atomically:YES];

- (NSString *)dataFilePath { NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *path = [documentsDirectory stringByAppendingPathComponent:@"children.plist"]; return path; }

like image 354
Mike Martin Avatar asked Feb 25 '23 17:02

Mike Martin


1 Answers

Assuming that the plist is stored on disk as a file, you can reopen it and load new contents by calling the arrayWithContentsOfFile method.

// Create the new dictionary that will be inserted into the plist.
NSMutableDictionary *nameDictionary = [NSMutableDictionary dictionary];
[nameDictionary setValue:@"John Doe" forKey:@"fullName"];
[nameDictionary setValue:@"555 W 1st St" forKey:@"address"];

// Open the plist from the filesystem.
NSMutableArray *plist = [NSMutableArray arrayWithContentsOfFile:@"/path/to/file.plist"];
if (plist == nil) plist = [NSMutableArray array];
[plist addObject:nameDictionary];
[plist writeToFile:@"/path/to/file.plist" atomically:YES];

The -(void)addObject:(id)object always inserts at the end of the array. If you need to insert at a specific index use -(void)insertObject:(id)object atIndex:(NSUInteger)index method.

[plist insertObject:nameDictionary atIndex:2];
like image 57
tidwall Avatar answered Mar 06 '23 17:03

tidwall