将新字典添加到我的 plist 文件中
根 ---- 数组
项目 0- 字典
全名 ---- String
地址 ---- String
第 1 项 ---- 词典
全名 ---- String
地址 ---- 字符串
我有一个看起来像那个的plist。在视图中,我有一个按钮,单击该按钮时我想添加新的“项目 2”或 3、4 或 5 等...我只想添加更多名称和地址。
今晚我花了 3 个小时寻找完美的例子,但没有找到。苹果财产清单样本太深了。我见过可能会接近的代码。
非常感谢
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] atomically:YES];
- (NSString *)dataFilePath { NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *path = [documentsDirectory stringByAppendingPathComponent:@"children.plist"]; 返回路径; }
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
假设 plist 作为文件存储在磁盘上,您可以通过调用 arrayWithContentsOfFile 方法重新打开它并加载新内容。
-(void)addObject:(id)object
始终插入到数组的末尾。如果需要在特定索引处插入,请使用-(void)insertObject:(id)object atIndex:(NSUInteger)index
方法。Assuming that the plist is stored on disk as a file, you can reopen it and load new contents by calling the
arrayWithContentsOfFile
method.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.