How do I group and then count a NSSet?
Question
How do I tackle grouping the records in a Core Data entity and then counting them so I can find the group with the highest count?
I have a 'set' which has many 'legs' each of which has one 'winner'. The question I am trying to answer is: Who has won the most legs.
Help is appreciated. Oh, and happy new year!
Solution
Iterate through the set and count the 'legs' for each 'winner'. Save the leg-counts in a dictionary:
NSMutableDictionary* legCount = [[NSMutableDictionary alloc] init];
NSNumber* count;
for (leg in legsSet) {
id winner = [leg objectForKey:@"winner"]; // assumes leg is a dictionary
if (count = [legCount objectForKey:winner]) {
[legCount setObject:[NSNumber numberWithInt:[count intValue]+1] forKey:winner];
} else {
[legCount setObject:[NSNumber numberWithInt:1] forKey:winner];
}
}
Now you need to find the key in the new dictionary with the highest value.
id winner = [[legCount keysSortedByValueUsingComparator:^(id obj1, id obj2) {
if ([obj1 intValue] > [obj2 intValue]) {
return (NSComparisonResult)NSOrderedDescending;
}
if ([obj1 intValue] < [obj2 intValue]) {
return (NSComparisonResult)NSOrderedAscending;
}
return (NSComparisonResult)NSOrderedSame;
}] lastObject];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow