对NSArray中自定义的对象进行排序
场景:Person类
@interface Person : NSObject @property (nonatomic, copy) NSString *name; @property (nonatomic, copy) NSString *surname; @property (nonatomic, strong) NSDate *dateOfBirth; @end
根据类中的任意对象作为排序的对象
使用NSComparator进行排序
NSArray *sortArray1 = [mPersonArray sortedArrayUsingComparator:^NSComparisonResult(Person *p1, Person *p2) { return [p1.surname compare:p2.surname]; }];
使用NSDescriptor进行排序
NSSortDescriptor *secondDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES]; NSArray *sortDescriptors = [NSArray arrayWithObjects:secondDescriptor, nil]; NSArray *sortArray2 = [mPersonArray sortedArrayUsingDescriptors:sortDescriptors];