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?

4

3 回答 3

21

您可以使用NSSortDescriptors 进行排序:

// 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];

您可以在此处阅读有关使用描述符进行排序的更多信息。

于 2013-06-24T02:53:29.013 回答
4

使用排序描述符的另一种方法是使用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;
    }
)];

请注意,我可能将最后两个向后。如果这将 No 值排序在 Yes 值之前,则交换最后两个返回值。

于 2013-06-24T03:06:46.233 回答
2

查找 NSSortDescriptors。创建两个,一个用于字符串,一个用于布尔值。然后将两者都添加到数组中。然后使用 NSArray 方法 sortedArrayWiyhDescriptors。

于 2013-06-24T02:54:25.470 回答