我们排序一般使用系统提供的或者是我们自定义的排序
但是遇到了复杂的排序 就会很麻烦的 这里我们可以采用 一种高级排序的方法
下面给大家介绍一下 很好用 直接上代码
#import <Foundation/Foundation.h>
@interface User : NSObject
@property (nonatomic, copy)NSString *name;
@property (nonatomic, assign)int age;
+ (User *)userWithName:(NSString *)name age:(int)age;
@end
#import "User.h"
@implementation User
+ (User *)userWithName:(NSString *)name age:(int)age
{
User *user = [[self alloc]init];
user.name = name;
user.age = age;
return user;
}
- (NSString *)description
{
return [NSString stringWithFormat:@"%@- %d",_name,_age];
}
@end
#import "ViewController.h"
#import "User.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
/*
*/
// [self sort];
[self sort2];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)sort2
{
//-w 表示不显示警告 在编译文件中修改
//先按照名字升序 如果名字一样 再按照年龄降序
User *u1 = [User userWithName:@"a1" age:10];
User *u2 = [User userWithName:@"a2" age:20];
User *u3 = [User userWithName:@"a3" age:60];
User *u4 = [User userWithName:@"a4" age:20];
User *u5 = [User userWithName:@"a5" age:50];
User *u6 = [User userWithName:@"a6" age:90];
NSArray *array = @[u1,u2,u3,u4,u5,u6];
//名字
NSSortDescriptor *nameSort = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES];
//年龄
NSSortDescriptor *ageSort = [NSSortDescriptor sortDescriptorWithKey:@"age" ascending:NO];
NSArray *sortArr = [array sortedArrayUsingDescriptors:@[nameSort,ageSort]];
for (User *user in sortArr) {
NSLog(@"%@",user);
}
}
- (void)sort
{
NSArray *array = @[@23,@90,@34,@56,@12];
// NSArray *sortArr = [array sortedArrayUsingSelector:@selector(compare:)];
// NSLog(@"%@",sortArr);//降序
//降序
NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:nil ascending:YES];
//排序
NSArray *sortArr = [array sortedArrayUsingDescriptors:@[sort]];
NSLog(@"%@",sortArr);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end