所以我有几个NSMutableDictionarys,并且特定字典的每个键/ valeu对都包含字符串或整数值。我想知道是否有办法迭代字典并连接值。在PHP中,我可以使用数组
来做这样的事情// either the dictionary holds all integers or all string values
$integer_array = array( 'a' => 2, 'b' => 9, 'c' => 2, 'd' => 0, 'e' => 1 );
foreach( $integer_array as $key => $value ) {
$concatenated_value .= $value;
}
// cast to int
$concatenated_value = ( int ) $concatenated_value;
// prints: 29201
echo $concatenated_value;
我也可以使用implode()
$concatenated_value = ( int )(implode("", $integer_array));
// prints: 29201
echo $concatenated_value;
iOS Objective-C有这样的东西吗?
答案 0 :(得分:2)
我不相信它有预定义的功能。对我来说,这似乎不是一件很常见的事情(在PHP中常见吗?)。我认为代码在理论上看起来像这样:
int finalVal = 0;
for (NSString *key in keyArray)
{
//If it is variable between NSString and NSNumber as you say, you will
//need to do type checking here.
NSNumber *numVal = [dictionary objectForKey:key];
int num = [numVal intValue];
//----Don't need this part if all values are single digits
while(num > 10)
{
finalVal += num;
finalVal *= 10;
num /= 10;
}
//--------------------------------------------------------
finalVal += num;
finalVal *= 10;
}
finalVal /= 10;
但是,由于没有订购字典,因此不太可能产生您想要的结果。我认为您需要一个不同的数据结构或一个按照插入顺序保存键的数组(但此时您也可以使用数组)。
编辑由于您使用的是有序的键阵列,我编辑了上面的答案。
答案 1 :(得分:2)
以下是你可以做到的事情(因为可可的字典没有订购,所以它的时间要长得多)。
NSMutableDictionary *d = [NSMutableDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:1], @"a",
[NSNumber numberWithInt:2], @"b",
[NSNumber numberWithInt:34], @"c",
[NSNumber numberWithInt:56], @"d",nil];
NSArray *sortedKeys = [[d allKeys] sortedArrayUsingSelector: @selector(compare:)];
NSMutableString *res = [NSMutableString string];
[sortedKeys enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
[res appendFormat:@"%d", [[d objectForKey:obj] intValue]];
}];
NSLog(@"%@", res);
这会打印123456