2012-07-20 51 views
2

因此,我有一對NSMutableDictionarys,每個特定字典的鍵/值對保持一個字符串或整數值。我想知道是否有方法遍歷字典並連接值。在PHP中我可以用一個陣列連接NSMutableDictionary轉換爲int,NSInteger和NSString的所有值

// 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

'NSDictionary'在Objective C不被排序,因此級聯將是隨機的,除非你進行排序鍵,然後在一個循環串聯值。 – dasblinkenlight 2012-07-20 01:40:08

+0

是的,循環內排序是我在想什麼 – 2012-07-20 01:45:15

回答

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; 

然而,這是非常不可能產生你想要,因爲字典是無序的結果。我認爲你需要一個不同的數據結構或者一個按照你插入的順序保存鍵的數組(但是在那時你可能只需要使用一個數組)。

編輯由於您使用的是有序數組,所以我編輯了上面的答案。

+0

是的我有另一個NSArray與迭代的鍵順序,並將鍵拉的字典的值,並將它連接起來 – 2012-07-20 01:46:56

+0

那麼,這隻會在一個小的變化碼。我將編輯 – borrrden 2012-07-20 01:57:30

+0

爲什麼finalVal * = 10;和finalVal/= 10;你能詳細瞭解一下它在做什麼嗎?否則很好的例子!是的,這在PHP中非常普遍 – 2012-07-20 02:06:03

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

+0

您能否演示如何在字典鍵/值顛倒的情況下執行此操作?所以'a'是關鍵,值是'1' – 2012-07-22 19:38:38

+0

@PhillPafford這就是代碼片段已經顯示的內容:數字是值,字符串是鍵(這是'dictionaryWithObjectsAndKeys:'的工作方式)。 – dasblinkenlight 2012-07-22 21:20:29

+0

我想我一直在看屏幕太長,我知道這個笑話謝謝! – 2012-07-22 21:30:59