数组内对象根据指定属性排序
Posted huaida
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了数组内对象根据指定属性排序相关的知识,希望对你有一定的参考价值。
参考:https://www.jianshu.com/p/732461f2439a
[arr sortUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) {
BTItemModel *item1 = (BTItemModel *)obj1;
BTItemModel *item2 = (BTItemModel *)obj2;
return [item1.rank compare:item2.rank];
}];
错误方式,结果是无序的:
[arr sortUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) {
BTItemModel *item1 = (BTItemModel *)obj1;
BTItemModel *item2 = (BTItemModel *)obj2;
if (item1.rank > item2.rank) {
return NSOrderedDescending;
} else {
return NSOrderedAscending;
}
return 0;
}];
规范方式:
NSArray *sortedArray = [array sortedArrayUsingComparator: ^(id obj1, id obj2) {
if ([obj1 integerValue] > [obj2 integerValue]) {
return (NSComparisonResult)NSOrderedDescending;
}
if ([obj1 integerValue] < [obj2 integerValue]) {
return (NSComparisonResult)NSOrderedAscending;
}
return (NSComparisonResult)NSOrderedSame;
}];
以上是关于数组内对象根据指定属性排序的主要内容,如果未能解决你的问题,请参考以下文章