An abstraction of comparison rules that describes how to sort collections of objects based on attributes common to all objects.

@interface NSSortDescriptor : NSObject <NSSecureCoding, NSCopying> {
@private
    NSUInteger _sortDescriptorFlags;
    NSString *_key;
    SEL _selector;
    id _selectorOrBlock;
}
Copy the code

First, initialization method

+ (instancetype)sortDescriptorWithKey:(nullable NSString *)key ascending:(BOOL) 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), the 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), the 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), the ios (4.0), watchos (2.0), tvos (9.0));Copy the code
  1. The basic parameters

Key: The critical path to perform the comparison, that is, the attribute to be compared. Ascending: The value is YES if the sort is in ascending order; otherwise, the value is NO.

  1. Optional parameters

Comparator: a block that compares rules. Selector: A function used to compare object attributes.

Second, sortedArrayUsingDescriptors: method

- (NSArray<ObjectType> *)sortedArrayUsingDescriptors:(NSArray<NSSortDescriptor *> *)sortDescriptors;
Copy the code

The parameter is passed an NSArray

, which is used as a set of collation rules, and the rules in the group are sorted from high priority to low priority, with the first rule having the highest priority.

3. Simple examples

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]; / / students by keyword first age (age) then score (grades) sort student = [[student sortedArrayUsingDescriptors: descriptors];Copy the code