当前位置: 动力学知识库 > 问答 > 编程问答 >

ios - How use NSSortdescriptor with a specific name first, then sorted on name?

问题描述:

Is it possible to use NSSortDescriptor to sort for a given value first, then sorted after the names of the objects?

NSArray *values = @[@"Fish",@"Me", @"Aardvark ", @"Turtle"]

Wanted result:

NSArray *sortedvalues = @[@"Me", @"Aardvark",@"Fish", @"Turtle"]

网友答案:

The sort descriptor is for when the contained object is KVO compliant (responds to valueForKey:). The way to do it with a comparator is...

NSArray *values = @[@"Fish",@"Me", @"Aardvark ", @"Turtle"];

NSComparisonResult (^comparator)(id,id) = ^(id left, id right) {
    if ([left isEqualToString:@"Me"]) return NSOrderedAscending;
    if ([right isEqualToString:@"Me"]) return NSOrderedDescending;
    return [left compare:right];
};
NSArray *sortedValues = [values sortedArrayUsingComparator:comparator];

I guess you can add an empty key path and use a sort descriptor (thanks to @Prince), but it seems like an extra step...

// define the comparator as above
NSSortDescriptor *sd = [NSSortDescriptor sortDescriptorWithKey:@"" ascending:YES comparator:comparator];
NSArray *sorted = [values sortedArrayUsingDescriptors:@[sd]];

EDIT

Say the elements of the array are really KVO objects. Then sort descriptor is a more natural fit. Just apply the idea given above with a key path to the strings, e.g.

NSDictionary *kvo0 = @{ @"prop": @"Fish"};
NSDictionary *kvo1 = @{ @"prop": @"Me"};
NSDictionary *kvo2 = @{ @"prop": @"Ardvark"};
NSDictionary *kvo3 = @{ @"prop": @"Turtle"};
NSArray *values = @[kvo0, kvo1, kvo2, kvo3];

NSComparisonResult (^comparator)(id,id) = ^(id left, id right) {
    if ([left isEqualToString:@"Me"]) return NSOrderedAscending;
    if ([right isEqualToString:@"Me"]) return NSOrderedDescending;
    return [left compare:right];
};
NSSortDescriptor *sd = [NSSortDescriptor sortDescriptorWithKey:@"prop" ascending:YES comparator:comparator];
NSArray *sorted = [values sortedArrayUsingDescriptors:@[sd]];

You'll want to change @"prop" to the key path upon which you want to sort the managed objects.

网友答案:

You can create a sort descriptor with a comparator like this...

NSSortDescriptor *sd = [NSSortDescriptor sortDescriptorWithKey:@"" ascending:YES comparator:^(NSString *string1, NSString *string2) {
    if ([string1 isEqualToString:@"Me"]){
        return NSOrderedAscending;
    }
    // edited thanks to @danh
    if ([string2 isEqualToString:@"Me"]){
        return NSOrderedDescending;
    }

    return [string1 compare:string2];
}

Then use this to sort your array.

If the sort descriptor is not required then just use the comparator to sort the array.

分享给朋友:
您可能感兴趣的文章:
随机阅读: