NSSortDescriptor可以根据数组中对象的属性来排序
为排序数组的每个属性创建NSSortDescriptor对象,将所有这些对象放入一个数组中,该数组将会在后面用作参数。使用NSArray类的sortedArrayUsingDescripors:方法并将NSSortDescriptor对象数组作为参数传递过去,会返回一个排好序的数组
新建一个Peron类
#import <Foundation/Foundation.h>
@interface Person : NSObject
@property (copy, nonatomic) NSString *name;
@property (assign, nonatomic) NSInteger age;
-(instancetype)initWithName:(NSString *)name age:(NSInteger)age;
-(void)printPerson;
#import "Person.h"
@implementation Person
-(instancetype)initWithName:(NSString *)name age:(NSInteger)age {
self = [super init];
if (self) {
self.name = name;
self.age = age;
}
return self;
}
-(void)printPerson {
NSLog(@"Name is %@ ageis %ld ",_name, _age);
}
Person *p1 = [[Person alloc] initWithName:@"aa" age:26];
Person *p2 = [[Person alloc] initWithName:@"bb" age:15];
Person *p3 = [[Person alloc] initWithName:@"cc" age:6];
Person *p4 = [[Person alloc] initWithName:@"dd" age:30];
Person *p5 = [[Person alloc] initWithName:@"ee" age:5];
NSArray *personArr = @[p1,p2,p3,p4,p5];
// 为每个属性创建NSSortDescriptor对象
NSSortDescriptor *sdAge = [NSSortDescriptor sortDescriptorWithKey:@"age" ascending:YES];
NSSortDescriptor *sdName = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES];
NSArray * sortedArray = [personArr sortedArrayUsingDescriptors:@[sdAge,sdName]];
// 为数组中每个元素执行方法,输出状态
[sortedArray makeObjectsPerformSelector:@selector(printPerson)];
输出结果
018-05-23 11:09:49.648013+0800 ArrayObjectSort[40836:2856845] Name is ee ageis 5
2018-05-23 11:09:49.648045+0800 ArrayObjectSort[40836:2856845] Name is cc ageis 6
2018-05-23 11:09:49.648061+0800 ArrayObjectSort[40836:2856845] Name is bb ageis 15
2018-05-23 11:09:49.648074+0800 ArrayObjectSort[40836:2856845] Name is aa ageis 26
2018-05-23 11:09:49.648087+0800 ArrayObjectSort[40836:2856845] Name is dd ageis 30