在循环中使用dictionaryWithObjectsAndKeys

时间:2015-10-12 21:10:57

标签: ios objective-c

尝试使用dictionaryWithObjectsAndKeys向字典添加值,我想使用for循环添加对象,我无法找到正确的方法,请帮助,使用for循环只显示最后的值,其他值不显示。看起来值是重叠的而不是附加的。

没有for循环的普通代码

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 (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 个答案:

答案 0 :(得分: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"]];
    }