添加到 NSMutableDictionary 而不替换相似的键
Add to NSMutableDictionary without replacing similar keys
我正在使用相同的键动态填充 NSMutableDictionary。但是,这样做会替换原始键值。我需要的是附加它而不是替换现有密钥。例如,我需要一个像
这样的结构
{
@"Key" : @"Value1",
@"Key" : @"Value2",
@"Key" : @"Value3"
}
我知道我可以将创建的每个 NSDictionary 添加到 NSMutableArray,但我的问题来了,因为我需要输入值为 NSDictionary。
目前我有以下内容替换了原来的值
NSMutableDictionary *ripDictionary = [[NSMutableDictionary alloc] init];
for(NSString *ripId in recievedRips){
//SOME OTHER CODE
ripDictionary[@"rip"] = keysAndAttributes;
[data addObject:ripDictionary];
}
每个字典只能有一个唯一键,因此如果您想要多个值与之关联,那么您可以将这些值添加到与该键关联的数组中。
if([aDictionary objectForKey:@"key"] != nil){
aDictionary[@"key"] = @[aDictionary[@"key"], bDictionary[@"key"]];
}else{
aDictionary[@"key"] = bDictionary[@"key"];
//OR make all aDictionary values array by default with a single value
//but you get the point
}
A key-value pair within a dictionary is called an entry. Each entry consists of one object that represents the key and a second object that is that key’s value. Within a dictionary, the keys are unique. That is, no two keys in a single dictionary are equal (as determined by isEqual:).
也许您可以修改代码以接受如下字典:
{
@"Key" : [
@"Value1",
@"Value2",
@"Value3"
]
}
我正在使用相同的键动态填充 NSMutableDictionary。但是,这样做会替换原始键值。我需要的是附加它而不是替换现有密钥。例如,我需要一个像
这样的结构 {
@"Key" : @"Value1",
@"Key" : @"Value2",
@"Key" : @"Value3"
}
我知道我可以将创建的每个 NSDictionary 添加到 NSMutableArray,但我的问题来了,因为我需要输入值为 NSDictionary。
目前我有以下内容替换了原来的值
NSMutableDictionary *ripDictionary = [[NSMutableDictionary alloc] init];
for(NSString *ripId in recievedRips){
//SOME OTHER CODE
ripDictionary[@"rip"] = keysAndAttributes;
[data addObject:ripDictionary];
}
每个字典只能有一个唯一键,因此如果您想要多个值与之关联,那么您可以将这些值添加到与该键关联的数组中。
if([aDictionary objectForKey:@"key"] != nil){
aDictionary[@"key"] = @[aDictionary[@"key"], bDictionary[@"key"]];
}else{
aDictionary[@"key"] = bDictionary[@"key"];
//OR make all aDictionary values array by default with a single value
//but you get the point
}
A key-value pair within a dictionary is called an entry. Each entry consists of one object that represents the key and a second object that is that key’s value. Within a dictionary, the keys are unique. That is, no two keys in a single dictionary are equal (as determined by isEqual:).
也许您可以修改代码以接受如下字典:
{
@"Key" : [
@"Value1",
@"Value2",
@"Value3"
]
}