2

そのため、いくつかの NSMutableDictionary があり、特定の辞書の各キーと値のペアは、文字列または整数値のいずれかを保持します。辞書を反復処理して値を連結する方法があるかどうかを知りたいです。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 にこのようなものはありますか?

4

2 に答える 2

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;

ただし、辞書は順序付けされていないため、これで目的の結果が得られる可能性はほとんどありません。別のデータ構造、または挿入した順序でキーを保持する配列が必要だと思います(ただし、その時点では配列を使用することもできます)。

編集キーの順序付けられた配列を使用しているため、上記の回答を編集しました。

于 2012-07-20T01:38:56.110 に答える
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

于 2012-07-20T01:51:45.277 に答える