我正在设置一个 NSDictionary 对象,以便 NSDictionary *scoreObject
的 key 具有玩家的名称,然后是 { date 的可变字典: 为其值评分}
。为了获取数据,我提取了在 Parse 中创建的自定义类,该类具有属性“Name”、“Score”和“createdAt”。
我正在尝试设置结构,以便上面的内容可以自动跨过 Parse 中的每一行数据进行拉取,但是当我有相同 Name
的两行数据时,我遇到了麻烦,它在我的 scoreObject
中设置为 keys。例如,如果 Bob 有两个分数和两个 createAt 日期,我如何才能简单地扩展值字典,以便两者仍然可以存储在键 =“Bob”下?
谢谢!
最佳答案
尝试这样的事情:
NSDictionary *dict;
//this is the dictionary you start with. You may need to make it an NSMutableDictionary instead.
//check if the dictionary contains the key you are going to modify. In this example, @"Bob"
if ([[dict allKeys] containsObject:@"Bob"]) {
//there already is an entry for bob so we modify its entry
NSMutableDictionary *entryDict = [[NSMutableDictionary alloc] initWithDictionary:dict{@"Bob"}];
[entryDict setValue:@(score) forKey:@"Date"];
[dict setValue:entryDict forKey:@"Bob"];
}
else {
//There is no entry for bob so we make a new one
NSDictionary *entryDict = @{@"Date": @(score)};
[dict setValue:entryDict forKey:@"Bob"];
}
关于iphone - 如何检查 NSDictionary 是否已经有一个键,然后在同一键下添加项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18007716/