Sign up ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free.

I have a NSArray of 'generic Objects' which contain the following properties

-name
-id
-type (question, topic or user)

How can I sort this array of generic object based on the generic object's type? E.g. I want to display all generic objects of type 'topic' on the top, followed by 'users' than 'questions'

share|improve this question
    
This has been answered several times: here, here, and here, for example. –  user1118321 Jan 9 '12 at 2:48
    
This question might have your answer: link –  jonkroll Jan 9 '12 at 2:49
    
Thanks, but in my case, I want specifically to push all objects with type = topic to the top so I can't really use ascending or descending sort in this case I guess. How can I do that? –  Zhen Jan 9 '12 at 2:58

1 Answer 1

up vote 5 down vote accepted

You'll need to define a custom sorting function, then pass it to an NSArray method that allows custom sorting. For example, using sortedArrayUsingFunction:context:, you might write (assuming your types are NSString instances):

NSInteger customSort(id obj1, id obj2, void *context) {
    NSString * type1 = [obj1 type];
    NSString * type2 = [obj2 type];

    NSArray * order = [NSArray arrayWithObjects:@"topic", @"users", @"questions", nil];

    if([type1 isEqualToString:type2]) {
        return NSOrderedSame; // same type
    } else if([order indexOfObject:type1] < [order indexOfObject:type2]) {
        return NSOrderedDescending; // the first type is preferred
    } else {
        return NSOrderedAscending; // the second type is preferred
    }   
}   

// later...

NSArray * sortedArray = [myGenericArray sortedArrayUsingFunction:customSort
                                                         context:NULL];

If your types aren't NSStrings, then just adapt the function as needed - you could replace the strings in the order array with your actual objects, or (if your types are part of an enumeration) do direct comparison and eliminate the order array entirely.

share|improve this answer
2  
You can also use NSArray's sortedArrayUsingComparator: method, which takes a block as its argument. That avoids needing to write a custom function, because you can put the same comparison code inside the block. –  Andrew Madsen Jan 9 '12 at 3:03
    
@AndrewMadsen: good point, thanks! There's actually a whole slew (well, five) similar comparison functions on NSArray - I picked this one pretty arbitrarily. Zhen: use whichever you're most comfortable with. –  Tim Jan 9 '12 at 3:05

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.