iOS 数组按照某一属性快速排序
2019-10-22 本文已影响0人
沐北
sortedArrayUsingComparator是一个block函数
可以用于对数组进行快速排序,对于model的操作类似
NSArray *sortArrayByIDStr = [self.dataSource sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
NSDictionary *pModel1 = obj1;
NSDictionary *pModel2 = obj2;
if ([self timeWithStr:pModel1[@"finishDate"]] < [self timeWithStr:pModel2[@"finishDate"]]){
if (self.timerInt == 0) {
return NSOrderedAscending;
}else{
return NSOrderedDescending;
}
}else{
if (self.timerInt == 0) {
return NSOrderedDescending;
}else{
return NSOrderedAscending;
}
}
}];
对于Comparator的返回值文档有下面的说明
NSOrderedAscending 升序
The left operand is smaller than the right operand.
NSOrderedSame 等于
The two operands are equal.
NSOrderedDescending 降序
The left operand is greater than the right operand
如果你期望的是值小的在前而值大的在后(升序),则可以在比较的时候返回NSOrderedAscending(-1),否则,就是NSOrderedDescending(1)。