I have an NSArray that contains nested NSArrays. Im looking for a way to sort the parent array according to the object count of the nested arrays in ascending order. so if [array1 count] is 4, [array2 count] is 2 and [array3 count] is 9, i would get : array2, array1, array3...

share|improve this question
up vote 9 down vote accepted

There are a few solutions, one of which is:

NSSortDescriptor *sd = [NSSortDescriptor sortDescriptorWithKey:@"@count"
                                                     ascending:YES];
NSArray *sds = [NSArray arrayWithObject:sd];
NSArray *sortedArray = [array sortedArrayUsingDescriptors:sds];
share|improve this answer
    
@Sam Indeed, and you can always use the @count collection operator for KVC compliant collections. – Bavarious Apr 30 '11 at 0:22
    
Ah, my apologies. I wasn't aware of that / misread your code. Very cool! – Sam Apr 30 '11 at 0:24
    
works great!.. i tried it earlier before asking the question but i was using @"count" as key and it was crashing... whats the secret with @"@count"??? – KDaker Apr 30 '11 at 11:26
3  
@KDaker NSArray doesn’t have a KVC compliant key called count. There is an instance method called -count but it isn’t a key in the KVC sense. That said, in Cocoa collections you can use special key paths called collection operators, and @count is one of them. – Bavarious Apr 30 '11 at 18:40
static NSInteger MONSortObjectsAscendingByCount(id lhs, id rhs, void* ignored) {
/* error checking omitted */
    const NSUInteger lhsCount = [lhs count];
    const NSUInteger rhsCount = [rhs count];

    if (lhsCount < rhsCount) {
        return NSOrderedAscending;
    }
    else if (lhsCount > rhsCount) {
        return NSOrderedDescending;
    }
    else {
        return NSOrderedSame;
    }
}

/* use if mutable, and you wnat it sorted in place */
- (void)sortUsingFunction:(NSInteger (*)(id, id, void *))compare context:(void *)context;

/* else use */
- (NSArray *)sortedArrayUsingFunction:(NSInteger (*)(id, id, void *))compare context:(void *)context;
share|improve this answer
1  
A function whose name doesn’t start with MON? Who are you and what have you done to Justin? – Bavarious Apr 30 '11 at 0:20
    
ugggghhhhhhhhhh!!!!!!! =p Justin has a headache today, and the build was finished. thanks for pointing that out -- i've fixed it now =) – justin Apr 30 '11 at 0:29

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.