坚持 成长 每日一篇
排序准备
这里我准备一个User对象用语我们后面排序时候使用
@interface User : NSObject
@property (nonatomic,readwrite,assign) NSInteger age ;
@property (nonatomic,readwrite,assign) NSInteger height;
-(NSComparisonResult)compare:(User*)user;
@end
@implementation User
-(id)initWithAge:(NSInteger)age height:(NSInteger)height
{
self = [super init];
if (self) {
self.age = age;
self.height = height;
}
return self;
}
/*NSComparisonResult是一个枚举
*NSOrderedAscending 升序 -1 不交换
*NSOrderedSame 相同 0 不交换
*NSOrderedDescending 降序 +1 可以理解为比较的两个位置交换
*/
//此函数实现的是按照age的生序排法
-(NSComparisonResult)compare:(User*)user
{
//此处的user指代的当前对象后面的某个对象
if (self.age > user.age) {
//如果当前对象大于后面对象交换两个对象,这是实现了生序排序,如果要实现降序则把函数体里的NSOrderedDescending和NSOrderedAscending交换
return NSOrderedDescending;
}else if(self.age < user.age)
{
return NSOrderedAscending;
}else
{
return NSOrderedSame;
}
}
-(NSString*)description
{
return [NSString stringWithFormat:@"age = %ld,height = %ld",self.age,self.height];
}
@end
在主函数里创建用于排序的数组
User *user1 = [[User alloc] initWithAge:10 height:180];
User *user2 = [[User alloc] initWithAge:15 height:150];
User *user3 = [[User alloc] initWithAge:20 height:180];
User *user4 = [[User alloc] initWithAge:30 height:134];
User *user5 = [[User alloc] initWithAge:30 height:154];
//创建用于排序的数组
NSArray *array = @[user3,user2,user4,user1,user5];
方法1:使用sortedArrayUsingSelector对数组进行排序
//方法1:使用sortedArrayUsingSelector对数组进行排序
//compare方法指的是数组里对象的方法。
NSArray * sortArray = [array sortedArrayUsingSelector:@selector(compare:)];
输出结果如下:
(
"age = 10,height = 180",
"age = 15,height = 150",
"age = 20,height = 180",
"age = 30,height = 134",
"age = 30,height = 154"
)
方法2:使用sortedArrayUsingComparator对数组进行排序
//方法2:使用sortedArrayUsingComparator对数组进行升序排序
NSArray *sortArray = [array sortedArrayUsingComparator:^NSComparisonResult(User *obj1, User *obj2) {
if (obj1.age > obj2.age) {
return NSOrderedDescending;
}else if(obj1.age < obj2.age)
{
return NSOrderedAscending;
}else
{
return NSOrderedSame;
}
}];
NSLog(@"sortArray =%@",sortArray);
输出结果如下:
(
"age = 10,height = 180",
"age = 15,height = 150",
"age = 20,height = 180",
"age = 30,height = 134",
"age = 30,height = 154"
)
方法3.通过描述器NSSortDescriptor定义排序规则
//方法3.通过描述器NSSortDescriptor定义排序规则 yes表示生序,no表示降序,这里的key也可是属性的属性哦
NSSortDescriptor *userAge =[NSSortDescriptor sortDescriptorWithKey:@"age" ascending:YES];
NSSortDescriptor *userHeight=[NSSortDescriptor sortDescriptorWithKey:@"height" ascending:YES];
//先按照user的age排序再按照user的height排序
NSArray *des=[NSArray arrayWithObjects:userAge,userHeight, nil];
//执行排序
NSArray *sortArray=[array sortedArrayUsingDescriptors:des];
NSLog(@"%@",sortArray);
输出结果如下:
(
"age = 10,height = 180",
"age = 15,height = 150",
"age = 20,height = 180",
"age = 30,height = 134",
"age = 30,height = 154"
)
注意:无论何种排序,都不会影响原来数组的排序,即demo中array的排序。排序的结果都是以一个新的数组返回。