iOS 数组排序
简单的字符串等排序
方式一:
NSArray *arr = @[@"Cecilia",@"Abbado",@"Baade"];
NSArray *sortArr = [arr sortedArrayUsingSelector:@selector(compare:)];
for (NSString *str in sortArr) {
NSLog(@"%@",str);
}
排序字符串同样不仅仅是字符串类型,NSNumber 效果也不错哦
NSArray *arr = @[@2,@5,@1];
方式二 :
NSArray *sortArr = [arr sortedArrayUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) {
return [(NSNumber *)obj1 compare:(NSNumber *)obj2];
}];
排序可以看到 是升序的。 默认的我们可以试一下这三个枚举,发现是NSOrderedDescending
会不会有人觉得NSOrderedDescending是降序 ,为什么 最后是 1 2 5 这个升序的结果?
因为这边是拿obj1 compare obj2,即用前者比较的后者,不是后者比较的前者
如果逻辑觉得不舒服,可以拿obj2 compare obj1 就是你想看到的效果了
那稍微高级点的 -- 对象的排序
一.首先定义对象
Person.h
@interface Person : NSObject
@property (nonatomic,copy) NSString *name;
@property (nonatomic,assign) int age;
@property (nonatomic,strong) NSNumber *weight;
-(instancetype)initWithName:(NSString *)name Age:(int)age Weight:(NSNumber *)weight;
Person.m
@implementation Person
-(instancetype)initWithName:(NSString *)name Age:(int)age Weight:(NSNumber *)weight{
if (self = [super init]) {
_name = name;
_age = age;
_weight = weight;
}
return self;
}
-(NSString *)description{
return [NSString stringWithFormat:@"名字%@==年纪%d==体重%@",_name,_age,_weight];
}
@end
二.开始排序
方式一
Person *p1 = [[Person alloc]initWithName:@"Cecilia" Age:20 Weight:@(80)];
Person *p2 = [[Person alloc]initWithName:@"Abbado" Age:8 Weight:@(65)];
Person *p3 = [[Person alloc]initWithName:@"Baade" Age:25 Weight:@(70)];
NSArray *arr = @[p1,p2,p3];
NSArray *sortArr = [arr sortedArrayUsingComparator:^NSComparisonResult(Person *obj1, Person *obj2) {
return [obj1.name compare:obj2.name] == NSOrderedDescending;
}];
for (Person *p in sortArr) {
NSLog(@"%@",p);
}
根据name 升序方式二
Person *p1 = [[Person alloc]initWithName:@"Cecilia" Age:20 Weight:@(80)];
Person *p2 = [[Person alloc]initWithName:@"Abbado" Age:8 Weight:@(65)];
Person *p3 = [[Person alloc]initWithName:@"Baade" Age:25 Weight:@(70)];
NSArray *arr = @[p1,p2,p3];
NSSortDescriptor *age_sort = [[NSSortDescriptor alloc]initWithKey:@"age" ascending:NO]; //NO代表降序,YES升序
NSArray *sortArr = [arr sortedArrayUsingDescriptors:@[age_sort]];
for (Person *p in sortArr) {
NSLog(@"%@",p);
}
根据age 降序我们注意到sortedArrayUsingDescriptors后面跟的参数是数组 那我们试一下
Person *p1 = [[Person alloc]initWithName:@"Cecilia" Age:20 Weight:@(80)];
Person *p2 = [[Person alloc]initWithName:@"Abbado" Age:8 Weight:@(65)];
Person *p3 = [[Person alloc]initWithName:@"Baade" Age:25 Weight:@(70)];
NSArray *arr = @[p1,p2,p3];
NSSortDescriptor *age_sort = [[NSSortDescriptor alloc]initWithKey:@"age" ascending:NO]; //NO代表降序,YES升序
NSSortDescriptor *name_sort = [[NSSortDescriptor alloc]initWithKey:@"name" ascending:YES]; //NO代表降序,YES升序
NSArray *sortArr = [arr sortedArrayUsingDescriptors:@[age_sort,name_sort]];
for (Person *p in sortArr) {
NSLog(@"%@",p);
}
我们更改一下age_sort 和 name_sort的 位置,打印如下
name升序,age降序我们看到两者打印效果是不同的,先后顺序代表着排序时候的优先顺序
有了这么个方法 ,再也不用自己吭哧吭哧了,苹果爸爸已经帮我们写好了,从此妈妈再也不用担心我的排序