我有一个下一个结构的plist:
-root (dictionary)
-windows (array)
我需要像这样在行窗口中添加项目:
-root (dictionary)
-windows (array)
-item0 value 1
-item1 value 2
我有以下几行:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"Windows.plist"];
NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile: path];
[data setObject:idWindow forKey:@"Windows"];
[data writeToFile: path atomically:YES];
但是他们只将Window行的类型更改为string并写入我插入的最后一个值。
我该怎么做?
罐
答案 0 :(得分:1)
data
是一个NSMutableDictionary。所以我们得到关键'windows'的数组:
NSMutableArray *windowsArray=[data objectForKey:@"windows"];
然后你可以像这样添加到这个数组:
[windowsArray addObject:myString];
在代码中执行[data setObject:idWindow forKey:@"Windows"];
时,用对象idWindow替换整个windows数组。这就是为什么你最终只得到你的最后一串。
以下是一个完整的代码片段,它从应用程序包中读取一个plist,在windows数组中添加2个字符串并将其保存在文档目录中:
NSMutableDictionary *data=[NSMutableDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"EmptyWindows" ofType:@"plist"]];
NSLog(@"data: %@", data);
NSMutableArray *windowsArray=[data objectForKey:@"windows"];
NSLog(@"windows: %@", windowsArray);
[windowsArray addObject:@"TestString1"];
[windowsArray addObject:@"TestString2"];
NSLog(@"windows after add: %@", windowsArray);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"Windows.plist"];
[data writeToFile:path atomically:YES];
希望这会有所帮助。