我正在寻找一种简单有效的方法来汇总NSDictionary中的所有值。
例如,如果我有NSDictionarys像:
NSDictionary * first = @{@"A": [NSNumber numberWithInt:1],
@"B": [NSNumber numberWithInt:2],
@"C": [NSNumber numberWithInt:3],
@"D": [NSNumber numberWithInt:4]};
NSDictionary * second = @{@"A": [NSNumber numberWithInt:1],
@"B": [NSNumber numberWithInt:2],
@"C": [NSNumber numberWithInt:3],
@"D": [NSNumber numberWithInt:4]};
我想获得一个NSD纪念日
NSDictionary * sum = @{@"A": [NSNumber numberWithInt:2],
@"B": [NSNumber numberWithInt:4],
@"C": [NSNumber numberWithInt:6],
@"D": [NSNumber numberWithInt:8]};
最佳答案
NSDictionary * first = @{@"A": [NSNumber numberWithInt:1],
@"B": [NSNumber numberWithInt:2],
@"C": [NSNumber numberWithInt:3],
@"D": [NSNumber numberWithInt:4]};
NSDictionary * second = @{@"A": [NSNumber numberWithInt:1],
@"B": [NSNumber numberWithInt:2],
@"C": [NSNumber numberWithInt:3],
@"D": [NSNumber numberWithInt:4]};
NSMutableDictionary *Third=[[NSMutableDictionary alloc]init];
for (NSString* key in [first allKeys]) {
NSLog(@"%@",key);
int a=[[first objectForKey:key]integerValue];
int b=[[second objectForKey:key]integerValue];
int c= a+b;
[Third setObject:[NSNumber numberWithInt:c] forKey:key];
}
NSLog(@"%@",Third);
更新了唯一密钥
NSArray *Key_of_First=[first allKeys];
NSArray *Key_of_Second=[second allKeys];
for (int j=0; j<Key_of_First.count; j++) {
int a=[[first objectForKey:[Key_of_First objectAtIndex:j]]integerValue];
int b=[[second objectForKey:[Key_of_Second objectAtIndex:j]]integerValue];
int c= a+b;
[Third setObject:[NSNumber numberWithInt:c] forKey:@"Your Key Name which you give"];
}
NSLog(@"%@",Third);