开发者

Adding a new dictionary to my plist file

开发者 https://www.devze.com 2023-01-27 13:42 出处:网络
Root---- Array   Item 0- Dictionary     fullName---- String    开发者_开发问答 address---- String

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


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

精彩评论

暂无评论...
验证码 换一张
取 消