ios - 将项目追加到 plist 中保存的 NSDictionary 中的现有键

标签 ios objective-c nsdictionary plist

如何将值从 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/

相关文章:

ios - 如何在 Swift 中将 NSDictionary 转换为 NSObject?

ios - 如何使用 Swift 3 在 iOS 10 上隐藏状态栏及其内容?

ios - 在表格 View 单元格中添加向下箭头

iphone - UISearchBar 键盘外观

iphone - ios 对象在 Debug 模式下会被释放,但在 Release 模式下不会被释放

objective-c - 向嵌套 NSDictionary 添加键

objective-c - 如何创建具有每周范围(超过 5 年)的 NSDate 的查找表

ios - 如何巧妙地为 UIView 生成 CGRects,例如 CSS div?

iphone - HmacSHA256 objective-c 加密

ios - 仅在单击完成按钮时将 UIPickerView 选择添加到 TextField