iOS 排序 NSSortDescriptor 的使用

1,087 阅读1分钟

NSSortDescriptor 用于指定集合内数据的排序规则 <按照指定的 key 进行排序>。 iOS 的集合对象均可使用 NSSortDescriptor 进行排序。

相关 API:

1.NSSet、NSMutableSet、NSArray、NSOrderedSet

-(NSArray<ObjectType> *)sortedArrayUsingDescriptors:(NSArray<NSSortDescriptor *> *)sortDescriptors

2.NSMutableArray、NSMutableOrderedSet

-(void)sortUsingDescriptors:(NSArray<NSSortDescriptor *> *)sortDescriptors;

示例:

1.创建 Student 对象

#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

@interface Student : NSObject

@property (assign, nonatomic) int stu_age;
@property (copy,   nonatomic) NSString *stu_name;
@end

NS_ASSUME_NONNULL_END

2.创建待排序的数据

#import "ViewController.h"
#import "Student.h"

@interface ViewController ()

@property (strong, nonatomic) NSMutableArray *students;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.students = [[NSMutableArray alloc] init];
    
    for (int i = 0; i < 10; i++) {
        
        int random_age  = arc4random()%3 + 10;
        int random_name = arc4random()%10;
        
        Student *student = [[Student alloc] init];
        student.stu_age  = random_age;
        student.stu_name = [NSString stringWithFormat:@"stu_%d", random_name];
        
        [self.students addObject:student];
    }
}

3.单一规则排序

- (void)sortByStuAge {
    // 按照 stu_age 进行排序
    // key --> 指定排序规则,ascending --> YES:升序   NO:降序
    NSSortDescriptor *sd = [[NSSortDescriptor alloc] initWithKey:@"stu_age" ascending:YES];
    [self.students sortUsingDescriptors:@[sd]];
    
    // 排序结果
    /**
     stu_age -> 10   stu_name -> stu_0
     stu_age -> 10   stu_name -> stu_6
     stu_age -> 10   stu_name -> stu_1
     stu_age -> 10   stu_name -> stu_4
     stu_age -> 10   stu_name -> stu_9
     stu_age -> 11   stu_name -> stu_5
     stu_age -> 11   stu_name -> stu_5
     stu_age -> 11   stu_name -> stu_9
     stu_age -> 11   stu_name -> stu_8
     stu_age -> 11   stu_name -> stu_9
     */
}

4.组合规则排序

API 排序规则参数是数组类型,所以我们可以一次性传入多个排序规则。这些规则按照在数组参数内的顺序依次生效

- (void)sortByCombination {
    // 先按照 stu_name 进行排序,当 stu_name 一致时,再按照 stu_age 进行排序
    NSSortDescriptor *sd_name = [[NSSortDescriptor alloc] initWithKey:@"stu_name" ascending:YES];
    NSSortDescriptor *sd_age  = [[NSSortDescriptor alloc] initWithKey:@"stu_age"  ascending:YES];
    [self.students sortUsingDescriptors:@[sd_name, sd_age]];
    
    // 排序结果
    /**
     stu_age -> 12   stu_name -> stu_0
     stu_age -> 12   stu_name -> stu_0
     stu_age -> 11   stu_name -> stu_3
     stu_age -> 10   stu_name -> stu_4
     stu_age -> 10   stu_name -> stu_4
     stu_age -> 11   stu_name -> stu_5
     stu_age -> 12   stu_name -> stu_5
     stu_age -> 10   stu_name -> stu_7
     stu_age -> 11   stu_name -> stu_7
     stu_age -> 12   stu_name -> stu_8
     */
}

以上。