gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:28:23 25 4
gpt4 key购买 nike

如何从 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
}

}

我在这里错过了什么?

非常感谢。

最佳答案

[dictionaryRecords setObject:tempArray forKey:@"Nathan"]tempArray 替换之前的值。

如果你想添加到现有数组,你必须检索它,制作一个可变副本,然后附加到它。

关于ios - 将项目附加到保存在 plist 中的 NSDictionary 中的现有键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22739534/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com