main.m
#import <Foundation/Foundation.h>
#import "Person.h"
/**
NSSortDescriptor 可以实现按照对象的属性进行排序;支持多个属性排序。比如我们有个Person对象,它有名字(name)和年龄(age)两个属性,我们需要按Person的age属性(降序)和name属性(升序)来输出Person对象数组信息
*/
void testSortDescriptor() {
NSMutableArray *mArrPerson = [[NSMutableArray alloc] initWithCapacity:];
Person *p = [[Person alloc] initWithName:@"KK" age:];
[mArrPerson addObject:p];
p = [[Person alloc] initWithName:@"Candy" age:];
[mArrPerson addObject:p];
p = [[Person alloc] initWithName:@"Wiky" age:];
[mArrPerson addObject:p];
p = [[Person alloc] initWithName:@"Stone" age:];
[mArrPerson addObject:p];
p = [[Person alloc] initWithName:@"Tom" age:];
[mArrPerson addObject:p];
p = [[Person alloc] initWithName:@"Sherlock" age:];
[mArrPerson addObject:p];
p = [[Person alloc] initWithName:@"Alex" age:];
[mArrPerson addObject:p];
p = [[Person alloc] initWithName:@"Keye" age:];
[mArrPerson addObject:p]; NSLog(@"按Person的age属性(降序)和name属性(升序)");
NSSortDescriptor *sortByAge = [[NSSortDescriptor alloc] initWithKey:@"age" ascending:NO];
NSSortDescriptor *sortByName = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
[mArrPerson sortUsingDescriptors:@[sortByAge, sortByName]];
for (Person *p in mArrPerson) {
NSLog(@"age=%ld, name=%@", p.age, p.name);
}
}
int main(int argc, const char * argv[]) {
@autoreleasepool {
testSortDescriptor();
}
return ;
}
Person.h
#import <Foundation/Foundation.h>
@interface Person : NSObject
@property (nonatomic, strong) NSString *name;
@property (nonatomic, assign) NSInteger age; - (id)initWithName:(NSString *)name age:(NSInteger)age;
@end
Person.m
#import "Person.h" @implementation Person
- (id)initWithName:(NSString *)name age:(NSInteger)age {
if (self = [super init]) {
_name = name;
_age = age;
}
return self;
}
@end
结果:
-- ::13.240 OCNSSortDescriptor[:] 按Person的age属性(降序)和name属性(升序)
-- ::13.241 OCNSSortDescriptor[:] age=, name=Stone
-- ::13.241 OCNSSortDescriptor[:] age=, name=Alex
-- ::13.241 OCNSSortDescriptor[:] age=, name=Keye
-- ::13.241 OCNSSortDescriptor[:] age=, name=Tom
-- ::13.242 OCNSSortDescriptor[:] age=, name=Sherlock
-- ::13.242 OCNSSortDescriptor[:] age=, name=Wiky
-- ::13.242 OCNSSortDescriptor[:] age=, name=KK
-- ::13.242 OCNSSortDescriptor[:] age=, name=Candy