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

时间:2010-12-01 05:46:06

标签: iphone plist nsdictionary

Root ----阵列
项目0-词典
fullName ---- String
地址----字符串
第1项----字典
fullName ---- 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];

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

1 个答案:

答案 0 :(得分: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];

-(void)addObject:(id)object始终插入数组的末尾。如果需要使用-(void)insertObject:(id)object atIndex:(NSUInteger)index方法在特定索引处插入。

[plist insertObject:nameDictionary atIndex:2];