我的应用程序中有自定义plist,我想在嵌套级别添加新密钥。
我该如何添加它?以编程方式?
这是我的plist文件的结构: : 怎么做到这一点?
请提前帮助和致谢。
答案 0 :(得分:2)
您无法编辑App-Bundle中的文件。您必须将其作为NSMutableDictionary
阅读,更改并将其保存到您的文档文件夹。
/*--- get bundle file ---*/
NSString *path = [[NSBundle mainBundle] pathForResource:@"Products" ofType:@"plist"];
NSMutableDictionary *rootDict = [[NSMutableDictionary alloc] initWithContentsOfFile:path];
/*--- set value with key ---*/
[rootDict setValue:@"NewKeyContent" forKeyPath:@"Mobiles.Brands.TheNewKey"];
/*--- get documents path ---*/
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *writablePath = [documentsDirectory stringByAppendingPathComponent:@"Products.plist"];
/*--- save file ---*/
[rootDict writeToFile:writablePath atomically: YES];
之后你将不得不从Documents目录中打开它,否则你将始终以干净的石板开始。
/*--- get documents file ---*/
NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *path = [docPath stringByAppendingPathComponent:@"Products.plist"];
NSMutableDictionary *rootDict = [[NSMutableDictionary alloc] initWithContentsOfFile:path];
/*--- set value with key ---*/
[rootDict setValue:@"NewKeyContent" forKeyPath:@"Mobiles.Brands.TheNewKey"];
/*--- get bundle file ---*/
[rootDict writeToFile:writablePath atomically: YES];
答案 1 :(得分:0)
使用NSMutableDictionary +(id / * NSDictionary * * /)dictionaryWithContentsOfFile:(NSString *)路径来创建字典。并使用 [字典setValue:@“new_value”forKeyPath:@“Mobiles.Brands.new_key”];
答案 2 :(得分:0)
正如其他人所说,你应该通过点击" +"在plist编辑器中添加新密钥。按钮。
如果你想用代码编辑你的plist,它会复杂得多。
plist文件被读入内存,其所有对象都是不可变的。您需要创建整个分支的可变副本,直到您要添加的对象。像这样:
//Make a mutable copy of the outermost dictionary
NSMutableDictionary *outer = [startingOuterDict mutableCopy];
//Create a mutable copy of the dictionary at key "Mobiles" and replace it in "outer"
NSMutableDictionary *mobiles = [outer[@"Mobiles"] mutableCopy];
outer[@"Mobiles"] = mobiles;
//Create a mutable copy of the dictionary at key "Brands" and replace it in "mobiles"
NSMutableDictionary *brands = [mobiles[@"Brands"] mutableCopy];
mobiles[@"Brands"] = brands;
//Finally, add a new key in the "Brands" dictionary
brands[@"newKey"] = @"Apple";
写一个" mutableDeepCopy"虽然很棘手但是很有可能。将字典,数组和集合的对象图中的所有容器转换为其可变等效项的方法。但是,在这种情况下你并不需要这样做。