objective-c - 将 NSMutableDictionary 中的所有值连接为 int、NSInteger 和 NSString
<p><p>所以我有几个 NSMutableDictionarys 并且特定字典的每个键/值对都保存一个字符串或整数值。我想知道是否有办法遍历字典并连接值。在 PHP 中,我可以使用数组来做这样的事情</p>
<pre><code>// 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;
</code></pre>
<p>我也可以使用 <a href="http://php.net/manual/en/function.implode.php" rel="noreferrer noopener nofollow">implode()</a>还有</p>
<pre><code>$concatenated_value = ( int )(implode("", $integer_array));
// prints: 29201
echo $concatenated_value;
</code></pre>
<p>iOS Objective-C 有类似的东西吗?</p></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>我不相信它有预定义的功能。对我来说,这似乎不是一件很常见的事情(在 PHP 中很常见吗?)。我想代码理论上应该是这样的:</p>
<pre><code>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 = ;
int num = ;
//----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;
</code></pre>
<p>但是,这不太可能产生您想要的结果,因为字典没有排序。我认为您需要一个不同的数据结构或一个数组,按照您插入它们的顺序保存键(但此时您最好只使用一个数组)。</p>
<p><strong>编辑</strong>由于您使用的是有序的键数组,因此我编辑了上面的答案。</p></p>
<p style="font-size: 20px;">关于objective-c - 将 NSMutableDictionary 中的所有值连接为 int、NSInteger 和 NSString,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/11571629/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/11571629/
</a>
</p>
页:
[1]