gpt4 book ai didi

ios - NSDictionary 中值的总和

转载 作者:行者123 更新时间:2023-11-28 20:12:43 27 4
gpt4 key购买 nike

我正在寻找一种有效且简单的方法来对 NSDictionary 中的所有值求和。

例如,如果我有像这样的 NSDictionary:

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]};

我想要一个 NSDictyonary

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);

更新了不同的 key

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);

关于ios - NSDictionary 中值的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19534388/

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