将项目附加到保存在plist中的NSDictionary中的现有密钥

fs_*_*gre 2 objective-c nsdictionary plist ios

如何从plist中将值附加到NSDictionary中的现有键?

我所拥有的基本上是一个保存在光盘中的带有几个键和值的plist,键是一些具有一个初始值的学生的名字.我试图做的不起作用是通过读取plist将更多项添加到现有键/学生,将其添加到临时NSDictionary,将临时数组附加到plist中的现有键但是当我保存时plist back它不起作用,它只保存最后两项并基本上删除该键的初始值.

这是我正在使用的代码......

- (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
    }

}
Run Code Online (Sandbox Code Playgroud)

我在这里错过了什么?

非常感谢提前.

Jos*_*ell 5

[dictionaryRecords setObject:tempArray forKey:@"Nathan"]替换以前的值tempArray.

如果要添加到现有数组,则必须检索它,创建可变副本并附加到它.