Axel0nf1r3 Axel0nf1r3 - 7 months ago 21
iOS Question

NSMutableArray, checking which Value is the most abundant?

How can I check which value in an

is the most frequent?

Array = "0,2,3,2,2,4

the value = "2".


Take a look at NSCountedSet this will help with your problem.

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

NSInteger maxCount = 0;
id maxObject = nil;

for (id object in countedSet) {
    if ([countedSet object] > maxCount) {
        maxCount = [countedSet countForObject:object];
        maxObject = object;

return maxObject;

This does sound like homework though.


If they are stored as strings instead of numbers then swap out NSNumber for NSString everything else works the same.


Actually, I just realised that it doesn't care about what object type it is...

Latest edit will work whatever the object is.