欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

排序(I)

程序员文章站 2022-06-11 11:43:21
NSSortDescriptor 排序 Person类 1 #import 2 3 @interface Person : NSObject 4 5 @property (nonatomic, copy) NSString *name; 6 @pr ......

NSSortDescriptor 排序

Person类

排序(I)
 1 #import <Foundation/Foundation.h>
 2 
 3 @interface Person : NSObject
 4 
 5 @property (nonatomic, copy) NSString *name;
 6 @property (nonatomic, assign) BOOL sex;
 7 @property (nonatomic, assign) double height;
 8 @property (nonatomic, assign) int age;
 9 
10 @end
View Code

排序调用方法

排序(I)
 1 - (void) test {
 2     
 3     NSArray *names = @[@"夏侯惇", @"貂蝉", @"诸葛亮", @"张三", @"李四", @"流火绯瞳", @"流火", @"李白", @"张飞", @"韩信", @"范冰冰", @"赵丽颖"];
 4     NSArray *ages = @[@32, @32, @45, @32, @32, @27, @15, @67, @55, @34, @44, @30];
 5     NSArray *heights = @[@170, @163, @180, @165, @163, @176, @174, @183, @186, @178, @167, @160];
 6     
 7     NSMutableArray *peoples = [NSMutableArray arrayWithCapacity:names.count];
 8     for (int i = 0; i<names.count; i++) {
 9         
10         Person *pe = [[Person alloc]init];
11         pe.name = names[i];
12         pe.age = [ages[i] intValue];
13         pe.height = [heights[i] doubleValue];
14         [peoples addObject:pe];
15     }
16     
17     
18     NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"age" ascending:YES];
19     
20     [peoples sortUsingDescriptors:@[sort]];
21     
22     // 输出排序结果
23     for (Person *people in peoples) {
24         NSLog(@"------------->age: %d,height: %f name: %@\n", people.age,people.height, people.name);
25     }
26     
27     
28 }
View Code

参数
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: 李白