将字典添加到plist

时间:2011-01-19 14:19:21

标签: iphone plist nsmutabledictionary

我希望有人可以帮助我,当我选择一个已经有效的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];

3 个答案:

答案 0 :(得分:0)

我认为你应该将所有词典放入一个可变数组中,该数组将成为plist的根对象。否则,您应该提出一个解决方案,为每个添加的条目生成新密钥。

当你需要添加东西时,你只需从plist中读取可变数组,添加它并保存它。根据我的记忆,在读/写plists时,数组和字典之间的方法非常相似。

答案 1 :(得分:0)

以下是我使用的内容:

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

答案 2 :(得分:0)

如果selectedEntry中的任何一个对象不是NSString,NSNumber,NSArray,NSDictionary等,那么写入将不会成功:

来自NSDictionary参考文档:

此方法在写出文件之前以递归方式验证所有包含的对象是属性列表对象(NSData,NSDate,NSNumber,NSString,NSArray或NSDictionary的实例),如果所有对象都不是,则返回NO属性列表对象,因为结果文件不是有效的属性列表。