
NSSortDescriptor 排序
Person类
#import <Foundation/Foundation.h> @interface Person : NSObject @property (nonatomic, copy) NSString *name;
@property (nonatomic, assign) BOOL sex;
@property (nonatomic, assign) double height;
@property (nonatomic, assign) int age; @end
排序调用方法
- (void) test { NSArray *names = @[@"夏侯惇", @"貂蝉", @"诸葛亮", @"张三", @"李四", @"流火绯瞳", @"流火", @"李白", @"张飞", @"韩信", @"范冰冰", @"赵丽颖"];
NSArray *ages = @[@, @, @, @, @, @, @, @, @, @, @, @];
NSArray *heights = @[@, @, @, @, @, @, @, @, @, @, @, @]; NSMutableArray *peoples = [NSMutableArray arrayWithCapacity:names.count];
for (int i = ; i<names.count; i++) { Person *pe = [[Person alloc]init];
pe.name = names[i];
pe.age = [ages[i] intValue];
pe.height = [heights[i] doubleValue];
[peoples addObject:pe];
} NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"age" ascending:YES]; [peoples sortUsingDescriptors:@[sort]]; // 输出排序结果
for (Person *people in peoples) {
NSLog(@"------------->age: %d,height: %f name: %@\n", people.age,people.height, people.name);
} }
参数
key : 排序key, 某个对象的属性名称; 如果对字符串进行排序, 则传nil
ascending : 是否升序, YES-升序, NO-降序
打印结果:
2018-05-19 19:11:43.904288+0800 Test[7264:81290] ------------->age: 15,height: 174.000000 name: 流火
2018-05-19 19:11:43.904436+0800 Test[7264:81290] ------------->age: 27,height: 176.000000 name: 流火绯瞳
2018-05-19 19:11:43.904527+0800 Test[7264:81290] ------------->age: 30,height: 160.000000 name: 赵丽颖
2018-05-19 19:11:43.904632+0800 Test[7264:81290] ------------->age: 32,height: 170.000000 name: 夏侯惇
2018-05-19 19:11:43.904732+0800 Test[7264:81290] ------------->age: 32,height: 163.000000 name: 貂蝉
2018-05-19 19:11:43.904832+0800 Test[7264:81290] ------------->age: 32,height: 165.000000 name: 张三
2018-05-19 19:11:43.904924+0800 Test[7264:81290] ------------->age: 32,height: 163.000000 name: 李四
2018-05-19 19:11:43.905017+0800 Test[7264:81290] ------------->age: 34,height: 178.000000 name: 韩信
2018-05-19 19:11:43.905098+0800 Test[7264:81290] ------------->age: 44,height: 167.000000 name: 范冰冰
2018-05-19 19:11:43.905186+0800 Test[7264:81290] ------------->age: 45,height: 180.000000 name: 诸葛亮
2018-05-19 19:11:43.905271+0800 Test[7264:81290] ------------->age: 55,height: 186.000000 name: 张飞
2018-05-19 19:11:43.905359+0800 Test[7264:81290] ------------->age: 67,height: 183.000000 name: 李白