1.使用NSSortDescriptor对象进行数组排序
//创建一个数组
NSArray *array = @[@"one", @"two", @"three", @"four", @"six"];
//创建一个排序条件,也就是一个NSSortDescriptor对象
//其中第一个参数为数组中对象要按照什么属性来排序(比如自身、姓名,年龄等)
//第二个参数为指定排序方式是升序还是降序
//ascending 排序的意思,默认为YES 升序
NSSortDescriptor *des = [[NSSortDescriptor alloc] initWithKey:@"self" ascending:YES];
NSArray *newArray = [array sortedArrayUsingDescriptors:@[des]];
NSLog(@"%@",newArray);
2.使用sortedArrayUsingDescriptors:方法实现把多个排序条件放到数组中,实现多条件排序,按数组先后顺序,先加入的优先级高
//创建一个Person类
Person *p1 = [[Person alloc] initWithName:@"zhonger" age:@"19"];
Person *p2 = [[Person alloc] initWithName:@"zhubada" age:@"11"];
Person *p3 = [[Person alloc] initWithName:@"zhubada" age:@"1"];
Person *p4 = [[Person alloc] initWithName:@"zhubada" age:@"33"];
Person *p5 = [[Person alloc] initWithName:@"hehehe" age:@"38"];
NSArray *person = @[p1, p2, p3, p4, p5];
NSSortDescriptor *des1 = [[NSSortDescriptor alloc]initWithKey:@"name" ascending:YES];
NSSortDescriptor *des2 = [[NSSortDescriptor alloc] initWithKey:@"age" ascending:NO];
NSArray *newArray1 = [person sortedArrayUsingDescriptors:@[des1,des2]];
NSLog(@"%@",newArray1);
3.使用sortedArrayUsingComparator进行数组排序
Comparator的返回结构枚举类型含义:
NSOrderedAscending//升序
The left operand is smaller than the right operand.
NSOrderedSame
The two operands are equal.
NSOrderedDescending//降序
The left operand is greater than the right operand.
直接使用代码块对字典里具体属性进行排序
NSString *arr = [arr sortedArrayUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) {
NSString *age1 = [obj1 objectForKey:@"age"];
NSString *age2 = [obj2 objectForKey:@"age"];
//转换成NSNumber便于直接使用compare:方法直接排序
NSNumber *num1 = [NSNumber numberWithInteger:age1];
NSNumber *num2 = [NSNumber numberWithInteger:age2];
//升序
NSComparisonResult result = [num1 compare:num2];
return result;
}];
NSLog(@"%@",arr);
//其中compare:内部实现类似于下(也可自定义对象的比较方法)
NSComparator cmp = ^(id obj1, id obj2) {
if ([obj1 integerValue] < [obj2 integerValue]) {
return (NSComparisonResult)NSOrderedAscending;
}else if ([obj1 integerValue] > [obj2 integerValue]) {
return (NSComparisonResult)NSOrderedDescending;
}else {
return (NSComparisonResult)NSOrderedSame;
};