所以我有几个 NSMutableDictionarys ,特定字典的每个键/值对都保存一个字符串或整数值。我想知道是否有一种方法可以迭代字典并连接值。在 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 有类似的东西吗?
最佳答案
我不相信有一个预定义的函数。对我来说,这似乎不是一件很常见的事情(在 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;
但是,这不太可能产生您想要的结果,因为字典没有排序。我认为您需要一个不同的数据结构或一个数组,按照您插入键的顺序保存键(但此时您最好只使用数组)。
编辑由于您使用的是有序的键数组,因此我编辑了上面的答案。
关于objective-c - 将 NSMutableDictionary 中的所有值连接为 int、NSInteger 和 NSString,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11571629/