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

标签 iphone plist nsdictionary

根 ---- 数组
项目 0- 字典
全名 ---- 字符串
地址 ---- 字符串
第 1 项 ---- 词典
全名 ---- 字符串
地址 ---- 字符串

我有一个看起来像那个的plist。在 View 中,我有一个按钮,单击该按钮时我想添加新的“项目 2”或 3、4 或 5 等...我只想添加更多名称和地址。

今晚我花了 3 个小时寻找完美的例子,但没有找到。苹果属性(property) list 样本太深了。我已经看到了可能会接近的代码。

非常感谢

NSMutableDictionary *nameDictionary = [NSMutableDictionary 字典]; [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] 原子地:YES];

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

最佳答案

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

关于iphone - 将新字典添加到我的 plist 文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4321567/

相关文章:

iPhone 离线网络应用程序缓存不起作用

iphone - Objective-C - 比 NSCaseInsensitiveSearch 更好的搜索?关键词? NSPredicate?

iphone - 从后台更新 plist

ios - 从 NSDictionary 访问 xml 值

iPhone - 关于调度计时器和计时的问题

iphone - Madgwick IMU算法在iphone上模拟

ios - Swift中如何保持Dictionary中数据的顺序?

ios - 如何在 IOS 中使用字典搜索核心数据..?

iphone - 为移动设备开发网站的最佳方式是什么?

ios - 如何更新现有的.plist?