阅读 126
iOS 使用NSSortDescriptor创建排序规则

iOS 使用NSSortDescriptor创建排序规则

比较规则的抽象,描述如何基于所有对象共有的属性对对象集合排序。

@interface NSSortDescriptor : NSObject <NSSecureCoding, NSCopying> {
@private
    NSUInteger _sortDescriptorFlags;
    NSString *_key;
    SEL _selector;
    id _selectorOrBlock;
}
复制代码

一、初始化方法

+ (instancetype)sortDescriptorWithKey:(nullable NSString *)key ascending:(BOOL)ascending API_AVAILABLE(macos(10.6), ios(4.0), watchos(2.0), tvos(9.0));
+ (instancetype)sortDescriptorWithKey:(nullable NSString *)key ascending:(BOOL)ascending selector:(nullable SEL)selector API_AVAILABLE(macos(10.6), ios(4.0), watchos(2.0), tvos(9.0));
+ (instancetype)sortDescriptorWithKey:(nullable NSString *)key ascending:(BOOL)ascending comparator:(NSComparator)cmptr API_AVAILABLE(macos(10.6), ios(4.0), watchos(2.0), tvos(9.0));

- (instancetype)initWithKey:(nullable NSString *)key ascending:(BOOL)ascending;
- (instancetype)initWithKey:(nullable NSString *)key ascending:(BOOL)ascending selector:(nullable SEL)selector;
- (instancetype)initWithKey:(nullable NSString *)key ascending:(BOOL)ascending comparator:(NSComparator)cmptr API_AVAILABLE(macos(10.6), ios(4.0), watchos(2.0), tvos(9.0));
复制代码
  1. 基本参数

key:执行比较的关键路径,即需要比较的属性。 ascending:如果按升序排序,则为YES,否则为NO。

  1. 可选参数

comparator:一个比较规则的block。 selector:一个函数,为比较对象属性时使用的方法。

二、sortedArrayUsingDescriptors: 方法

- (NSArray<ObjectType> *)sortedArrayUsingDescriptors:(NSArray<NSSortDescriptor *> *)sortDescriptors;
复制代码

参数传入一个NSArray<NSSortDescriptor *>,作为一组排序规则,组内的规则优先级从高到低排列,第一个规则优先级最高。

三、简单示例

举例一个学生类,学生有属性年龄,姓名,考试成绩,对其进行排序

Student *s1 = [[Student alloc] initWithName:@"zhangsna" age:@"19" score:@"90"];
    
Student *s2 = [[Student alloc] initWithName:@"lisi" age:@"20" score:@"87"];
    
Student *s3 = [[Student alloc] initWithName:@"wangwu" age:@"21" score:@"93"];
    
NSArray *student = @[s1, s2, s3];

NSSortDescriptor *age = [NSSortDescriptor sortDescriptorWithKey:@"age" ascending:YES];
NSSortDescriptor *score=[NSSortDescriptor sortDescriptorWithKey:@"score" ascending:YES];

NSArray *descriptors = [NSArray arrayWithObjects: age, score]; //学生先按关键字age(年龄)再按score(成绩)排序

student = [[student sortedArrayUsingDescriptors: descriptors];
复制代码
文章分类
iOS
文章标签