标签:
一、数组
1.简单的数组排序(sortedArrayUsingSelector:)
NSArray *array = @[@123,@7889,@231]; NSArray *sortArray =[array sortedArrayUsingSelector:@selector(compare:)]; NSLog(@"%@",sortArray);
//字符串对比,会根据逐个字符进行对比排序
NSComparisonResult compare(id obj1,id obj2){ if (obj1 < obj2) { return NSOrderedAscending;//升序 } if (obj1 > obj2) { return NSOrderedDescending;//降序 }else return NSOrderedSame;//相同 }
2.使用block语法(sortedArrayUsingCompartor)
NSArray *sortArray2 = [array sortedArrayUsingComparator: ^NSComparisonResult(id _Nonnull obj1,id _Nonnull obj2){ if (obj1 < obj2) { return NSOrderedAscending;//升序 } if (obj1 > obj2) { return NSOrderedDescending;//降序 }else return NSOrderedSame;//相同 }];
3.高级排序(sortedArrayUsingDescriptors:)
main
Person *p1 = [[Person alloc] init]; p1.name = @"Jack"; p1.age = 17; Person *p2 = [[Person alloc]initWithName:@"Mary" andAge:19]; Person *p3 = [[Person alloc]initWithName:@"Hop" andAge:22]; NSArray *obj = [NSArray arrayWithObjects:p1,p2,p3,nil];
//创建排序描述器 NSSortDescriptor *nameDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES]; NSSortDescriptor *ageDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"age" ascending:YES]; //将描述器再装起来 NSArray < NSSortDescriptor *>*descriptorArray =[NSArray arrayWithObjects:nameDescriptor ,ageDescriptor,nil]; NSArray *sortArray3 = [obj sortedArrayUsingDescriptors:descriptorArray]; NSLog(@"%@",sortArray3);
.h
#import <Foundation/Foundation.h> @interface Person : NSObject @property (nonatomic,copy) NSString *name; @property (nonatomic,assign) int age; - (id)initWithName:(NSString *)name andAge:(int)age; - (NSString *)description; @end
.m
#import "Person.h" @implementation Person - (id)initWithName:(NSString *)name andAge:(int)age{ if (self = [super init]) { _name = name; _age = age; } return self; } - (NSString *)description{ return [NSString stringWithFormat:@"name = %@ age = %d",_name,_age]; } @end
二、字典
1.第一种排序方法
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:@23232,@"A",@7878,@"B", nil]; [dict keysSortedByValueUsingSelector:@selector(compare:)]; NSLog(@"%@",dict);
2.第二种排序方法
[dict keysSortedByValueUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) { if (obj1 < obj2) { return NSOrderedAscending;//升序 } if (obj1 > obj2) { return NSOrderedDescending;//降序 }else return NSOrderedSame;//相同
}]; NSLog(@"%@",dict);
标签:
原文地址:http://www.cnblogs.com/lsa0913/p/5714591.html