Mike Martin
Mike Martin

Reputation: 453

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

Upvotes: 4

Views: 6152

Answers (1)

tidwall
tidwall

Reputation: 6949

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

Upvotes: 8

Related Questions