NSArray *arr = @[
@"234",
@"123",
@"235",
@"133"
];
NSArray *sortArr = [arr sortedArrayUsingSelector:@selector(compare:)];
NSLog(@"%@",sortArr);//用要排序的原数组调用实例方法,第二个参数,是方法选择,如果数组的元素都是字符串,那么直接用compare:就行
//block(代码块)排序
NSArray *sortArr2 = [arr sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
return [obj1 compare:obj2];//根据比较结果,如果结果是1,则交换
}];
NSLog(@"%@",sortArr2);
main函数
Student *s = [[Student alloc] init];
s.name = @"zhangyu";
s.age = 20;
Student *s1 = [[Student alloc] init];
s1.name = @"zhangyuzi";
s1.age = 18;
Student *s2 = [[Student alloc] init];
s2.age = 21;
s2.name = @"lirongsheng";
NSArray *arr = @[
s,
s1,
s2
];
//自定义对象排序
NSArray *stuArr = [arr sortedArrayUsingSelector:@selector(compareWithAge:)];
NSLog(@"%@",stuArr);
}
return 0;
}
main.h
#import <Foundation/Foundation.h>
@interface Student : NSObject
@property (nonatomic, strong) NSString *name;
@property (nonatomic, assign) int age;
//自定义比较方法(排序时调用),要遵循compare:方法
//格式:-(NSComparisonResult)方法名:(要比较的类名 *)参数名
-(NSComparisonResult)compareWithName:(Student *)stu;
-(NSComparisonResult)compareWithAge:(Student *)stu;
@end
main.m
#import "Student.h"
@implementation Student
-(NSString *)description{
return [NSString stringWithFormat:@"%@,%d",_name,_age];
}
//比较方法的实现
-(NSComparisonResult)compareWithName:(Student *)stu{
//对象的比较结果就相当于属性比较结果,self,最开始代表第0个元素,后面再比较时,代表交换后的满足条件的对象
/*
0 self a[0];
1 self a[1]
2 self a[2]
*/
//当self放在第一个参数是,代表升序,放在第二个参数时,代表降序 只有result为1的时候才进行交换
NSComparisonResult result = [stu.name compare: self.name];
return result;
}
-(NSComparisonResult)compareWithAge:(Student *)stu{
NSComparisonResult result;
if (self.age < stu.age) {
result = 1;
}else{
result = -1;
}
return result;
}
@end