Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I've seen this question:
NSMutableArray counting occurances of objects and then re-arange the array

The solution comes very close to what i need.

The solution I'm referring to:

NSInteger countedSort(id obj1, id obj2, void *context) {
   NSCountedSet *countedSet = context;
   NSUInteger obj1Count = [countedSet countForObject:obj1];
   NSUInteger obj2Count = [countedSet countForObject:obj2];

   if (obj1Count > obj2Count) return NSOrderedAscending;
   else if (obj1Count < obj2Count) return NSOrderedDescending;
   return NSOrderedSame;
}    

and:

NSMutableArray *array = …;

NSCountedSet *countedSet = [[[NSCountedSet alloc] initWithArray:array]
autorelease];

[array sortUsingFunction:countedSort context:countedSet];    

The sort returns proper sorted array by count, but i need the count either included or in another array sorted ascending.

share|improve this question
up vote 1 down vote accepted

A solution could be to simply query the counted set for the count of any object, to build an array that keep track of the counts:

// This after having sorted the array:
NSMutableArray* counts= [NSMutableArray arrayWithCapacity: array.count];
for(id object in array) {
    [counts addObject: @([countedSet countForObject: object]) ];
}
share|improve this answer
A simple solution. Thanks! – GameDevGuru 2 days ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.