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
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.
Use this code to add the three arrays into one dictionary with your specific keys.
NSDictionary *yourDictinary = @{@"one": array0, @"two": array1, @"three": array3};
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.
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];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With