将字典添加到 plist
我希望有人可以帮助我,当我选择一个已经可以工作但只写入一个条目的 tableView 行时,我想将一本字典写入 plist。但每个选择都应该添加。
到目前为止我的代码:
NSString *plistPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"liste.plist"];
NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithObjectsAndKeys:
[selectedEntry valueForKey:NAME], @"Name",
[selectedEntry valueForKey:add], @"Add"
, nil];
[tempArray writeToFile:plistPath atomically:YES];
我找到了解决问题的方法。 我在 viewDidLoad 中初始化数组并用 plist 填充它,现在它可以工作了......
self.tempArray = [NSMutableArray arrayWithContentsOfFile:plistPath];
并更改
[dictionary writeToFile:plistPath atomically:YES];
为
[tempArray writeToFile:plistPath atomically:YES];
I hope someone can help me with that I want to write a dictionary to a plist when i select a tableView row which already works but it only writes one entry. but every selection should be added.
my code so far:
NSString *plistPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"liste.plist"];
NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithObjectsAndKeys:
[selectedEntry valueForKey:NAME], @"Name",
[selectedEntry valueForKey:add], @"Add"
, nil];
[tempArray writeToFile:plistPath atomically:YES];
I found a way to solve the problem.
I initialize the Array in the viewDidLoad and filled it with the plist and now it works....
self.tempArray = [NSMutableArray arrayWithContentsOfFile:plistPath];
and changed
[dictionary writeToFile:plistPath atomically:YES];
to
[tempArray writeToFile:plistPath atomically:YES];
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
发布评论
评论(3)
九歌凝2024-10-19 23:13:39
这是我使用的:
NSFileManager *manager = [NSFileManager defaultManager];
NSMutableDictionary *dict;
dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:
VALUE1, KEY1,
VALUE2, KEY2,
VALUE3, KEY3,
VALUE4, KEY4,
nil ];
NSString *err = nil;
NSData *plist;
plist = [NSPropertyListSerialization dataFromPropertyList:dict format:NSPropertyListBinaryFormat_v1_0 errorDescription:&err];
if([manager fileExistsAtPath:@"YourPlist.plist"] == NO){
[manager createFileAtPath:[NSString stringWithFormat:@"YourPlist.plist"] contents:plist attributes:nil];
}
[manager release];
~没有更多了~
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
我认为你应该将所有字典放入一个可变数组中,该数组将成为 plist 的根对象。否则,您应该想出一个解决方案来为添加的每个条目生成新密钥。
当您需要添加内容时,只需从 plist 中读取可变数组,添加到其中并保存即可。据我所知,数组和字典在读/写 plist 时的方法非常相似。
I think that you should put all dictionaries into a mutable array which would be the root object of the plist. Otherwise you should come up with a solution to generate new keys for each entry added.
When you need to add stuff you just read up the mutable array from the plist, add to it, and save it. From what I recall, the methods are very similar between arrays and dictionaries when reading/writing plists.