Group duplicates in NSArray

I have an NSArray containing custom objects, for example:

[A, A, B, C, A, D, E, B, D]

What is the best way to group these elements so that the end result is as follows?

A: 3
B: 2
C: 1
D: 2
E: 1

Please note that duplicates are different instances with the same properties, but for this I redefined isEqual:.

+5
source share
2 answers

The easiest way is to use NSCountedSet. You can use [NSCountedSet setWithArray:myArray]to create a counted set of your array, and then you can iterate over the contents of the set to find out the number of each object in the set. Please note that it will not be sorted.

, -hash, , -isEqual:. -compare:, .

, , :

void printCountOfElementsInArray(NSArray *ary) {
    NSCountedSet *set = [NSCountedSet setWithArray:ary];
    NSArray *objs = [[set allObjects] sortedArrayUsingSelector:@selector(compare:)];
    for (id obj in objs) {
        NSLog(@"%@: %d", obj, [set countForObject:obj]);
    }
}
+8

NSCountedSet.

NSCountedSet *countedSet = [[NSCountedSet alloc] initWithArray:myArray];
NSUInteger countForA = [countedSet countForObject:@"A"];
NSLog(@"A: %u", countForA);
+7

All Articles