NSSortDescriptor 排序 Person類 1 #import <Foundation/Foundation.h> 2 3 @interface Person : NSObject 4 5 @property (nonatomic, copy) NSString *name; 6 @pr ...
NSSortDescriptor 排序
Person類
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 @endView Code
排序調用方法
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: 李白