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 BOOL
s 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?
You can use NSSortDescriptor
s 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With