main.m
1 #import <Foundation/Foundation.h> 2 #import "Person.h" 3 /** 4 NSSortDescriptor 可以实现按照对象的属性进行排序;支持多个属性排序。比如我们有个Person对象,它有名字(name)和年龄(age)两个属性,我们需要按Person的age属性(降序)和name属性(升序)来输出Person对象数组信息 5 */ 6 void testSortDescriptor() { 7 NSMutableArray *mArrPerson = [[NSMutableArray alloc] initWithCapacity:5]; 8 Person *p = [[Person alloc] initWithName:@"KK" age:23]; 9 [mArrPerson addObject:p]; 10 p = [[Person alloc] initWithName:@"Candy" age:22]; 11 [mArrPerson addObject:p]; 12 p = [[Person alloc] initWithName:@"Wiky" age:27]; 13 [mArrPerson addObject:p]; 14 p = [[Person alloc] initWithName:@"Stone" age:32]; 15 [mArrPerson addObject:p]; 16 p = [[Person alloc] initWithName:@"Tom" age:28]; 17 [mArrPerson addObject:p]; 18 p = [[Person alloc] initWithName:@"Sherlock" age:27]; 19 [mArrPerson addObject:p]; 20 p = [[Person alloc] initWithName:@"Alex" age:29]; 21 [mArrPerson addObject:p]; 22 p = [[Person alloc] initWithName:@"Keye" age:28]; 23 [mArrPerson addObject:p]; 24 25 NSLog(@"按Person的age属性(降序)和name属性(升序)"); 26 NSSortDescriptor *sortByAge = [[NSSortDescriptor alloc] initWithKey:@"age" ascending:NO]; 27 NSSortDescriptor *sortByName = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES]; 28 [mArrPerson sortUsingDescriptors:@[sortByAge, sortByName]]; 29 for (Person *p in mArrPerson) { 30 NSLog(@"age=%ld, name=%@", p.age, p.name); 31 } 32 } 33 int main(int argc, const char * argv[]) { 34 @autoreleasepool { 35 testSortDescriptor(); 36 } 37 return 0; 38 }
Person.h
1 #import <Foundation/Foundation.h> 2 @interface Person : NSObject 3 @property (nonatomic, strong) NSString *name; 4 @property (nonatomic, assign) NSInteger age; 5 6 - (id)initWithName:(NSString *)name age:(NSInteger)age; 7 @end
Person.m
1 #import "Person.h" 2 3 @implementation Person 4 - (id)initWithName:(NSString *)name age:(NSInteger)age { 5 if (self = [super init]) { 6 _name = name; 7 _age = age; 8 } 9 return self; 10 } 11 @end
结果:
1 2015-03-28 12:27:13.240 OCNSSortDescriptor[1276:49262] 按Person的age属性(降序)和name属性(升序) 2 2015-03-28 12:27:13.241 OCNSSortDescriptor[1276:49262] age=32, name=Stone 3 2015-03-28 12:27:13.241 OCNSSortDescriptor[1276:49262] age=29, name=Alex 4 2015-03-28 12:27:13.241 OCNSSortDescriptor[1276:49262] age=28, name=Keye 5 2015-03-28 12:27:13.241 OCNSSortDescriptor[1276:49262] age=28, name=Tom 6 2015-03-28 12:27:13.242 OCNSSortDescriptor[1276:49262] age=27, name=Sherlock 7 2015-03-28 12:27:13.242 OCNSSortDescriptor[1276:49262] age=27, name=Wiky 8 2015-03-28 12:27:13.242 OCNSSortDescriptor[1276:49262] age=23, name=KK 9 2015-03-28 12:27:13.242 OCNSSortDescriptor[1276:49262] age=22, name=Candy
时间: 2024-10-11 05:51:13