Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort Array Based on Two Parameters

I have an array of objects that consist of two properties: an NSString and a BOOL. I'd like to sort this array so that all the BOOLs that are YES appear before all the bools that are NO. Then I'd like for the list of objects that have the BOOL YES to alphabetized and I'd also like for the objects with the NO to be alphabetized. Is there some sort of library that can accomplish this in objective c? If not what is the most efficient way to do this?

like image 773
Ser Pounce Avatar asked Jun 24 '13 02:06

Ser Pounce


2 Answers

You can use NSSortDescriptors to do the sorting:

// Set ascending:NO so that "YES" would appear ahead of "NO"
NSSortDescriptor *boolDescr = [[NSSortDescriptor alloc] initWithKey:@"boolField" ascending:NO];
// String are alphabetized in ascending order
NSSortDescriptor *strDescr = [[NSSortDescriptor alloc] initWithKey:@"strField" ascending:YES];
// Combine the two
NSArray *sortDescriptors = @[boolDescr, strDescr];
// Sort your array
NSArray *sortedArray = [myArray sortedArrayUsingDescriptors:sortDescriptors];

You can read more about sorting with descriptors here.

like image 68
Sergey Kalinichenko Avatar answered Oct 07 '22 09:10

Sergey Kalinichenko


An alternative to using sort descriptors is to use an NSComparator:

NSArray *myObjects = ... // your array of "Foo" objects
NSArray *sortedArray = [myObjects sortedArrayUsingComparator:^(Foo *obj1, Foo *obj2) {
    if ((obj1.boolProp && obj2.boolProp) || (!obj1.boolProp && !obj2.boolProp)) {
        // Both bools are either YES or both are NO so sort by the string property
        return [obj1.stringProp compare:obj2.stringProp];
    } else if (obj1.boolProp) {
        // first is YES, second is NO
        return NSOrderedAscending;
    } else {
        // second is YES, first is NO
        return NSOrderedDescending;
    }
)];

Please note that I may have the last two backward. If this sorts the No values before the Yes values then swap the last two return values.

like image 25
rmaddy Avatar answered Oct 07 '22 11:10

rmaddy