iOS为对象数组排序

NSSortDescriptor可以根据数组中对象的属性来排序
为排序数组的每个属性创建NSSortDescriptor对象,将所有这些对象放入一个数组中,该数组将会在后面用作参数。使用NSArray类的sortedArrayUsingDescripors:方法并将NSSortDescriptor对象数组作为参数传递过去,会返回一个排好序的数组

创建一个OS X 的Application,选择Command Line Tool,语言为Objective-C

  1. 首先创建一个Person类用于排序
    Person.h
@interface Person : NSObject
@property (nonatomic, copy) NSString *firstName;
@property (nonatomic, copy) NSString *lastName;
@property (nonatomic, assign) NSInteger age;
-(instancetype)initWithFirstName:(NSString *)fName lastName:(NSString *)lName age:(NSInteger) age;
/**
 *  输出状态
 */
-(void)printState;
@end

Person.m

@implementation Person
-(instancetype)initWithFirstName:(NSString *)fName lastName:(NSString *)lName age:(NSInteger)age {
    self = [super init];
    if (self) {
        self.firstName = fName;
        self.lastName = lName;
        self.age = age;
    }
    return self;
}  
-(void)printState {
    NSLog(@"Name is %@ %@ is %ld years old",_firstName, _lastName, _age);
}
@end
  1. 在main.m中排序
#import "Person.h"
int main(int argc, const char * argv[]) {
    Person *p1 = [[Person alloc] initWithFirstName:@"Wenxuan" lastName:@"Huo" age:21];
    Person *p2 = [[Person alloc] initWithFirstName:@"MaHa" lastName:@"B" age:30];
    Person *p3 = [[Person alloc] initWithFirstName:@"MeKe" lastName:@"C" age:30];
    Person *p4 = [[Person alloc] initWithFirstName:@"MaLian" lastName:@"A" age:30];
    Person *p5 = [[Person alloc] initWithFirstName:@"HoHo" lastName:@"A" age:40];
    Person *p6 = [[Person alloc] initWithFirstName:@"Guo" lastName:@"Zhong" age:5000];

    // 包含所有Person的数组
    NSArray *peopleArray = @[p1, p2, p3, p4, p5, p6];

    // 为每个属性创建NSSortDescriptor对象
    NSSortDescriptor * sdFirstName = [NSSortDescriptor sortDescriptorWithKey:@"firstName" ascending:YES];
    NSSortDescriptor * sdLastName = [NSSortDescriptor sortDescriptorWithKey:@"lastName" ascending:YES];
    NSSortDescriptor * sdAge = [NSSortDescriptor sortDescriptorWithKey:@"age" ascending:YES];

    // 设置排序优先级,并组成数组。这里优先级最高为age,之后是firstName
    NSArray * sortedArray = [peopleArray sortedArrayUsingDescriptors:@[sdAge, sdLastName, sdFirstName]];
    // 为数组中每个元素执行方法,输出状态
    [sortedArray makeObjectsPerformSelector:@selector(printState)];
     
    return 0;
}

输出结果:

Name is Wenxuan Huo is 21 years old
Name is MaLian A is 30 years old
Name is MaHa B is 30 years old
Name is MeKe C is 30 years old
Name is HoHo A is 40 years old
Name is Guo Zhong is 5000 years old

下面测试另一种排序方式

    // 优先级最高为firstName,之后是age
    NSArray * sortedArray = [peopleArray sortedArrayUsingDescriptors:@[sdLastName, sdAge, sdFirstName]];
    [sortedArray makeObjectsPerformSelector:@selector(printState)];

输出结果:

Name is MaLian A is 30 years old
Name is HoHo A is 40 years old
Name is MaHa B is 30 years old
Name is MeKe C is 30 years old
Name is Wenxuan Huo is 21 years old
Name is Guo Zhong is 5000 years old

Nice

你可能感兴趣的:(iOS为对象数组排序)