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
-hashfor 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: