objective-c - 将 NSMutableDictionary 中的所有值连接为 int、NSInteger 和 NSString

标签 objective-c ios casting concatenation nsmutabledictionary

所以我有几个 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/

相关文章:

iphone - 从我的 iPhone 应用程序中使用的 iTunes 库中删除/隐藏文件

ios - 从一组按钮中标记以使用标记参数打开新 View

ios - NSDateComponents 与 timeIntervalSince

ios - iOS 项目中的 Pods-resources.sh 权限被拒绝

ios - 如何让 react-native 在 Mac OS X El Capitan 中使用主机文件?

c++模板类型推导在强制转换运算符中失败

ios - WKWebView 检查 HTML 表单提交

iphone - 如何在 iOS 中使用 jar

asp.net - 无法转换类型为“System.Collections.Generic.List”的对象

java - 为什么以下代码会自动装箱为错误的类型并进行编译?