- block(代码块)排序
NSArray*sortArr2
= [arr
sortedArrayUsingComparator:^NSComparisonResult(idobj1,id
obj2) {
return[obj1compare:obj2];//根据比较结果,如果结果是1,则交换
}];
里面的 return[obj1compare:obj2];
也可以换成
NSComparisonResultres = -1;
if([obj1
money] > [obj2money]) { //附带属性
res =1;
}
returnres;
- compare
NSArray*arr =@[@"234",
@"123",
@"235",
@"133"];NSArray*sortArr = [arrsortedArrayUsingSelector:@selector(compare:)];NSLog(@"%@",sortArr);//用要排序的原数组调用实例方法,第二个参数,是方法选择,如果数组的元素都是字符串,那么直接用compare:就行
//自定义对象排序 (排序时调用),要遵循compare:方法main.mNSArray*stuArr = [arrsortedArrayUsingSelector:@selector(compareWithAge:)];NSLog(@"%@",stuArr);.h格式:-(NSComparisonResult)方法名:(要比较的类名*)参数名-(NSComparisonResult)compareWithName:(Student*)stu;-(NSComparisonResult)compareWithAge:(Student*)stu;.m//对象的比较结果就相当于属性比较结果,self,最开始代表第0个元素,后面再比较时,代表交换后的满足条件的对象//当self放在第一个参数是,代表升序,放在第二个参数时,代表降序 只有result为1的时候才进行交换
-
- 字符串
-(NSComparisonResult)compareWithName:(Student*)stu{NSComparisonResult result = [stu.namecompare:self.name];return result;}上面内部 NSComparisonResultresult = [stu.namecompare:self.name]; 语句可换下面语句NSComparisonResultres = -1;if ([self.titlecompare:t.title] == -1) {res =1;}returnres;
-(NSComparisonResult)compareWithAge:(Student*)stu{NSComparisonResult result;if (self.age< stu.age) {
result =result = 1;
}}else{
result = -result = -1;
}
}return result;}
- //描述器排序
//先创建排序条件:key对应要排序的对象的属性名字
NSSortDescriptor *sort = [NSSortDescriptorsortDescriptorWithKey:@"title"ascending:YES];
NSSortDescriptor *sort1 = [NSSortDescriptorsortDescriptorWithKey:@"money"ascending:NO];
//将描述条件放入排序数组(用于盛放排序条件,可以多个)
//先按年龄升序排序,名字一样的情况,再按工资降序排序
NSArray *desArr = @[sort,sort1];
NSArray *sortArr1 = [arr sortedArrayUsingDescriptors:desArr];
NSLog(@"--->%@",sortArr1);
//按照教师所带学生的分数排序
NSSortDescriptor *sort2 = [NSSortDescriptorsortDescriptorWithKey:@"s.score"ascending:YES];
NSArray *scoreArr = @[sort2];
NSArray *arr10 = [arr sortedArrayUsingDescriptors:scoreArr];
NSLog(@"--%@",arr10);
Teacher.h
#import"Student.h"
@property(nonatomic,strong)Student*s;
Teacher.m
-(NSString*)description{
return[NSStringstringWithFormat:@"%@,%f,%f",_title,_money,_s.score];
}
return[NSStringstringWithFormat:@"%@,%f,%f",_title,_money,_s.score];
}
Student.h
@property(nonatomic,assign)floatscore;
版权声明:本文为博主原创文章,未经博主允许不得转载。