将新字典添加到我的plist文件中

Mik*_*tin 4 iphone nsdictionary plist

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

我有一个看起来像那个的plist.在一个视图中我有一个按钮,当点击时我想添加一个新的"第2项"或3或4或5等...我只想添加更多的名称和地址.

我今晚花了3个小时寻找完美的例子但是很短暂.Apple财产列出的样本太深了.我见过可能会接近的代码.

非常感谢

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];
Run Code Online (Sandbox Code Playgroud)

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

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];
Run Code Online (Sandbox Code Playgroud)

tid*_*all 8

假设plist作为文件存储在磁盘上,您可以通过调用该arrayWithContentsOfFile方法重新打开它并加载新内容.

// 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];
Run Code Online (Sandbox Code Playgroud)

所述-(void)addObject:(id)object总是插入在阵列的端部.如果需要在特定索引处插入使用-(void)insertObject:(id)object atIndex:(NSUInteger)index方法.

[plist insertObject:nameDictionary atIndex:2];
Run Code Online (Sandbox Code Playgroud)