如何将值从 plist 附加到 NSDictionary 中的现有键?
我所拥有的基本上是一个保存在光盘中的plist,其中包含一些键和值,键是一些具有一个初始值的学生的名字。我想做的不起作用的是通过读取 plist 将更多项目附加到现有键/学生,将其添加到临时 NSDictionary,将临时数组附加到 plist 中的现有键,但是当我保存plist 返回它不起作用,它只保存最后两项,并且基本上删除该键的初始值。
这是我正在使用的代码...
- (IBAction)testing:(id)sender
{
NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [dirPaths objectAtIndex:0];
NSString *fullPath = [documentsPath stringByAppendingPathComponent:@"studentsRecords.plist"];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:fullPath];
if(fileExists)
{
NSMutableDictionary *dictionaryRecords = [[NSMutableDictionary alloc]initWithContentsOfFile:fullPath];
NSLog(@"Items for Nathan: %@",[dictionaryRecords objectForKey:@"Nathan"]);// here the output is, Items for Nathan: Ruler
// which make sense since I only had one initial record for Nathan in my plist,
// Here, I want to add two more items to the key Nathan by appending an arry to
// NSMutableDictionary (dictionaryRecords) but it doesnt work
NSArray *tempArray = @[@"NoteBook", @"Pencil"];
[dictionaryRecords setObject:tempArray forKey:@"Nathan"];
[dictionaryRecords writeToFile:fullPath atomically:YES];
// when I check the plist after saving this, I only see the last two values, NoteBook and Pencil
// instead of the three that I'm expecting, Ruler, NoteBook and Pencil
}
}
我在这里缺少什么?
提前非常感谢。
最佳答案
[dictionaryRecords setObject:tempArray forKey:@"Nathan"]
用 tempArray
替换之前的值。
如果您想添加到现有数组,您必须检索它,制作一个可变副本,然后追加到它。
关于ios - 将项目追加到 plist 中保存的 NSDictionary 中的现有键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22739534/