Search code examples
ioscocoa-touchnsarraynsdictionary

Adding objects to dictionary in a loop overwrites previous values


I have three NSArrays, and I want to combine them all into a single NSDictionary. The problem is that as I iterate through the arrays and create the dictionary, it overwrites the previous object. In the end I only have one object in my dictionary. What am I doing wrong? Here's my code:

NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
for(int i=0; i<[array0 count]; i++) {
    [dict setObject:[array0 objectAtIndex:i] 
             forKey:@"one"];
    [dict setObject:[array1 objectAtIndex:i] f
              orKey:@"two"];
    [dict setObject:[array2 objectAtIndex:i] 
             forKey:@"three"];
}

Maybe this will clarify what I mean... this is the result I'm going for:

{one = array0_obj0, two = array1_obj0, three = array2_obj0},
{one = array0_obj1, two = array1_obj1, three = array2_obj1},
{one = array0_obj2, two = array1_obj2, three = array2_obj2}, 
etc

Thanks


Solution

  • Here ya go:

    NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
    for(int i=0; i<[array0 count]; i++) {
        [dict setObject:[array0 objectAtIndex:i] forKey:[NSString stringWithFormat:@"arr0_%d", i]];
        [dict setObject:[array1 objectAtIndex:i] forKey:[NSString stringWithFormat:@"arr1_%d", i]];
        [dict setObject:[array2 objectAtIndex:i] forKey:[NSString stringWithFormat:@"arr2_%d", i]];
    }
    

    Edit - with revised question:

    self.array0 = @[@"Array0_0",@"Array0_1",@"Array0_2", @"Array0_3"];
    self.array1 = @[@"Array1_0",@"Array1_1",@"Array1_2", @"Array1_3"];
    self.array2 = @[@"Array2_0",@"Array2_1",@"Array2_2", @"Array2_3"];
    
    NSMutableArray *finalArray = [[NSMutableArray alloc] init];
    
    for (int i=0; i< [_array0 count]; i++) {
    
        NSDictionary *dict = @{@"one":[_array0 objectAtIndex:i], @"two":[_array1 objectAtIndex:i],@"three":[_array2 objectAtIndex:i]};
        [finalArray addObject:dict];
    }
    
    NSLog(@"finalArray = %@", [finalArray description]);