Choppin Broccoli Choppin Broccoli - 5 months ago 123
Objective-C Question

NSCountedSet order by count

Does anyone know how to take an NSCountedSet of objects and create an array of those objects in order by their object count? (highest count to lowest)

    NSCountedSet *countedSet = [[NSCountedSet alloc] initWithArray:array2];

    NSMutableArray *dictArray = [NSMutableArray array];
    [countedSet enumerateObjectsUsingBlock:^(id obj, BOOL *stop) {
        [dictArray addObject:@{@"object": obj,
                               @"count": @([countedSet countForObject:obj])}];

    NSLog(@"Objects sorted by count: %@", [dictArray sortedArrayUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"count" ascending:NO]]]);

In the code above, array2 is an array of of 100 random strings, each with two letters. sortedArrayUsingDescriptors:, returns a sorted array, in this case it is sorted in descending order by the count of the objects.