Iphone 将字典添加到plist
我希望有人能帮助我,当我选择一个tableView行时,我想为plist编写一个字典,该行已经运行,但它只写一个条目。但每个选项都应该添加 到目前为止,我的代码是:Iphone 将字典添加到plist,iphone,plist,nsmutabledictionary,Iphone,Plist,Nsmutabledictionary,我希望有人能帮助我,当我选择一个tableView行时,我想为plist编写一个字典,该行已经运行,但它只写一个条目。但每个选项都应该添加 到目前为止,我的代码是: NSString *plistPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"liste.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];
到
我认为应该将所有字典放入一个可变数组中,该数组将是plist的根对象。否则,您应该想出一个解决方案,为每个添加的条目生成新的密钥 当您需要添加内容时,只需从plist读取可变数组,添加到其中,然后保存它。据我回忆,在读/写plists时,数组和字典的方法非常相似。以下是我使用的方法:
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];
如果selectedEntry中的任一对象不是NSString、NSNumber、NSArray、NSDictionary等,则写入将不会成功: 从NSDictionary参考文档中:
此方法在写入文件之前递归验证所有包含的对象是否都是NSData、NSDate、NSNumber、NSString、NSArray或NSDictionary的属性列表对象实例,如果所有对象都不是属性列表对象,则返回否,因为生成的文件不是有效的属性列表。为什么不使用NSUserDefaults?你可以很容易地读写这样的信息。但是为什么我可以写两个条目,然后我得到这个错误呢。所有SelectedEntry都是NSMutibleString。从代码片段中可以看出,字典中似乎只有两个条目在编写中:name和Add。另外,您得到的错误文本是什么?只有字典被写了2次。当我选择一个表行时,它应该将字典及其条目写入plist,这样我就可以看到我已经选择的内容。但是,当我选择第三行时,我会得到错误消息,从那以后,每次尝试读取或写入plistFrank时,它都会崩溃。弗兰克:在这一点上,我不知所措。我会确保selectedEntry值未被保留,即您碰巧重用的已发布值。
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];