pixelfreak
pixelfreak

Reputation: 17844

Grouping 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 items so the end result resembles this?

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

Please note that the duplicates are all different instances that have the same properties, but I have overridden isEqual: for this.

Upvotes: 5

Views: 436

Answers (2)

Lily Ballard
Lily Ballard

Reputation: 185801

The simplest way is probably to use an NSCountedSet. You can use [NSCountedSet setWithArray:myArray] to produce a counted set of your array, and then you can iterate over the set's contents to find out the count of each object in the set. Note that it won't be sorted.

Also note that you'll need to provide a sensible implementation of -hash for this to work, since you only said you overrode -isEqual:. You also need to override -compare: if you need a sorted list of results.

Here's a quick method that takes your array and prints the count of each element, sorted:

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

Upvotes: 8

Ole Begemann
Ole Begemann

Reputation: 135578

Use the NSCountedSet class.

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

Upvotes: 7

Related Questions