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.
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]);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With