Reputation: 219
I have three NSArray
s, 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
Upvotes: 3
Views: 2817
Reputation: 14780
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];
}
Upvotes: 5
Reputation: 14427
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]);
Upvotes: 4
Reputation: 54
If you want many dictionary but only three keys, you should save each dict in an array.
Upvotes: -1
Reputation: 5881
You're reusing the keys ("one", "two" and "three")
through each iteration of the loop. Keys in an NSDictionary
have to be unique.
Upvotes: 3