I have a NSMutableArray with objects of type NSMutableDictionary,
the NSMutableDictionary contains 2 keys
-Airlines (string)
-Rating (integer)
I have an NSMutableArray with all the objects and what i need is to Sum the rating of all the airline companies repeated objects, an example:
Airline Rating
A 2
B 3
B 4
C 5
The end result array will be the A = 2, C = 5 and the Sum of B´s that is equal to 7.
My code so far:
for (int i = 0; i < arrayMealRating.count; ++i) {
NSMutableDictionary *item = [arrayMealRating objectAtIndex:i];
NSLog(@"item=%@",item);
for (int j = i+1; j < arrayMealRating.count; ++j)
{
if ([[item valueForKey:@"Airline"] isEqualToString:[arrayMealRating objectAtIndex:j]]){
NSMutableDictionary *item = [arrayMealRating objectAtIndex:j];
NSMutableDictionary *item1 = [arrayMealRating objectAtIndex:i];
NSInteger auxCount = [[item valueForKey:@"setMealRating"] integerValue] + [[item1 valueForKey:@"setMealRating"] integerValue];
NSMutableDictionary *aux = [NSMutableDictionary dictionaryWithObjectsAndKeys:[item valueForKey:@"Airline"], @"Airline"
,[NSString stringWithFormat:@"%d",auxCount], @"setMealRating"
,nil];
NSLog(@"aux=%@",aux);
[arrayMealRating replaceObjectAtIndex:i withObject:aux];
}
}
}
A bit messy i know but i dont know how to work with NSMutableDictionary, any help will be much appreciated, Thanks in Advance!
Incase you dont want to change how your storing the data, heres how you would do it using key-value coding. Heres the dirrect link to the documentation for @distinctUnionOfObjects and @sum.
This gives the following output