Adding a new dictionary to the plist file

Root ---- Array
Item 0 - Dictionary
fullName ---- String
Address ---- String
Paragraph 1 ---- Dictionary
fullName ---- String
Address ---- String

I have a plist that looks something like this. In the view, I have a button, when I click on it, I want to add a new "Item 2" or 3 or 4 or 5, etc. I just want to add some more names and addresses.

I spent 3 hours finding the perfect example, but came up with a short one. Sample Apple property lists were too deep. I saw code that probably comes close.

Many thanks

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

code>

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

+4
source share
1 answer

Assuming plist is stored on disk as a file, you can reopen it and load new content 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]; 

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

 [plist insertObject:nameDictionary atIndex:2]; 
+8
source

All Articles