2015-10-12 107 views
0

嘗試使用dictionaryWithObjectsAndKeys將值添加到字典中,我想使用for循環添加對象,並且我無法找到正確的出路,請大家幫忙,使用for循環只顯示最後一個值值不會出現。看起來像值過度並且沒有被追加。dictionaryWithObjectsAndKeys inside loop

正常代碼,而無需爲循環

toListDictUnSorted = [NSDictionary dictionaryWithObjectsAndKeys: 
           [NSArray arrayWithObjects:[NSNumber numberWithInt:316], @"USD 50000", @"English", nil], @"USA", 
           [NSArray arrayWithObjects:[NSNumber numberWithInt:194], @"USD 12000", @"Portugese", nil], @"Brazil", 
           [NSArray arrayWithObjects:[NSNumber numberWithInt:1210], @"USD 1592", @"Hindi", nil], @"India", 
           [NSArray arrayWithObjects:[NSNumber numberWithInt:1353], @"USD 6075", @"Chinese", nil], @"China", 
           [NSArray arrayWithObjects:[NSNumber numberWithInt:143], @"USD 14037", @"Russian", nil], @"Russia", 
           [NSArray arrayWithObjects:[NSNumber numberWithInt:59], @"USD 33115]", @"Italian", nil], @"Italy", 
           [NSArray arrayWithObjects:[NSNumber numberWithInt:63], @"USD 38591", @"English", nil], @"Great Britain", 
           [NSArray arrayWithObjects:[NSNumber numberWithInt:29], @"USD 25000", @"Arabic", nil], @"Saudi Arabia", 
           nil]; */ 

for循環代碼

for (int i = 0; i < [_toData count]; i++) 
     { 

      toListDictUnSorted = [NSMutableDictionary dictionaryWithObjectsAndKeys: 
            [NSArray arrayWithObjects:[NSNumber numberWithInt:meters], [[_toData objectAtIndex:i] valueForKey:@"name"], nil], [[_toData objectAtIndex:i] valueForKey:@"name"] , nil]; 



     } 

回答

1

您應該使用一個NSMutableDictionary,而不是一個NSDictionary

編輯的:

你想這樣的:

NSMutableDictionary *toListDictUnSorted = [[NSMutableDictionary alloc] init]; 
    for (int i = 0; i < [_toData count]; i++) 
    { 
     [toListDictUnSorted setObject:[NSArray arrayWithObjects:[NSNumber numberWithInt:meters], [[_toData objectAtIndex:i] valueForKey:@"name"], nil] forKey:[[_toData objectAtIndex:i] valueForKey:@"name"]]; 
    } 
+0

嘗試使用NSMutableDictionary,但只有最後一個值被添加,這是在for循環內。 – Max

+0

您必須更改Dictionary而不是Array的類型。 NSMutableDictionary * dict = [NSMutableDictionary new]; [dict setObject:[NSArray arrayWithObjects:[NSNumber numberWithInt:316],@「USD 50000」,@「English」,nil] forKey:@「USA」]; for循環應該工作,然後使用「setObject:forKey:」 – alexm

+0

然後,可能你使用相同的密鑰爲每個迭代 – alexm