使用NSComparator进行排序
comparator实际上是用一个block对象作比较操作。它的定义如下所示:
typedef NSComparisonResult (^NSComparator)(id obj1, id obj2);
上面的参数(obj1、obj2)就是我们将要做比较的对象。block返回的结果为NSComparisonResult类型来表示两个对象的顺序。
要对整个数组做排序,则需要使用NSArray的sortArrayUsingComparator:方法,如下代码所示:
NSArray *sortedArray = [self.persons sortedArrayUsingComparator:^NSComparisonResult(Person *p1, Person *p2){
return [p1.surname compare:p2.surname];
}];
具体上一段项目代码:
NSArray *sortedArray = [self.nearByDrugstoressortedArrayUsingComparator:^NSComparisonResult(DrugstoreModel *model1,DrugstoreModel *model2){
return [model1.distancefloatValue] < [model2.distancefloatValue];
}];
self.nearByDrugstores = sortedArray;
结果为 返回距离从远到近的排序
NSArray *sortedArray = [self.nearByDrugstores sortedArrayUsingComparator:^NSComparisonResult(DrugstoreModel *model1, DrugstoreModel *model2){
if (model1.consulting_num < model2.consulting_num) {
return NSOrderedDescending;
} else {
return NSOrderedAscending;
}
}];
self.nearByDrugstores = sortedArray;
或者我们用这样的代码,效果一致:
NSArray *sortedArray = [self.nearByDrugstores sortedArrayUsingComparator:^NSComparisonResult(DrugstoreModel *model1, DrugstoreModel *model2){
if (model1.consulting_num > model2.consulting_num) {
return NSOrderedAscending;
} else {
return NSOrderedDescending;
}
}];
self . nearByDrugstores = sortedArray;