Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 907
dbarrett Avatar asked Mar 21 '26 09:03

dbarrett


1 Answers

Issue

You are inserting and replacing the same object at the specific key. So all what dictionary has is its last object at the last index.

Solution

Use this code to add the three arrays into one dictionary with your specific keys.

NSDictionary *yourDictinary = @{@"one": array0, @"two": array1, @"three": array3};

Edit

If you need to add objects of your NSMutableArrays to one NSDictionary you can follow the answer posted by @ElJay, but that's not a good practice, since you are dealing with multiple objects with unique keys.

Update

To do that thing, we are talking about a single NSMutableArray and multiple NSDictinarys.

Follow this code:

NSMutableArray *allObjects = [NSMutableArray new];
for(int i=0; i<[array0 count]; i++) {
    dict = @{@"one": array0[i], @"two": array1[i], @"three": array2[i]};
    [allObjects addObject:dict];
}
like image 171
E-Riddie Avatar answered Mar 23 '26 01:03

E-Riddie