简体   繁体   中英

How do I group and then count a NSSet?

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!

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];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM