8

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?

0

3 Answers 3

21

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.

Sign up to request clarification or add additional context in comments.

Comments

4

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.

Comments

2

Look up NSSortDescriptors. Create two, one for the string, one for the bool. Then add both to an array. Then use NSArray method sortedArrayWiyhDescriptors.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.