说明
- 1.sortedArrayUsingComparator这个方法本身就是按递增的方式排序。
- 2.返回的返回值(NSOrderedAscending 不交换,NSOrderedSame 不交换,NSOrderedDescending 交换)。
- 3.NSOrderedSame 不做改变
例如:object1 < object2 返回:NSOrderedDescending 则交换(变为object2,object1),数组变为降序 。返回NSOrderedAscending,两者不交换, 数组变为升序。
1. 降序
// 降序
NSArray *tMlist = @[@1,@5,@2,@6,@3,@7,@9];
NSArray *tArray = [tMlist sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
NSNumber *tNumber1 = (NSNumber *)obj1;
NSNumber *tNumber2 = (NSNumber *)obj2;
// 因为不满足sortedArrayUsingComparator方法的默认排序顺序,则需要交换
if ([tNumber1 integerValue] < [tNumber2 integerValue]) return NSOrderedDescending;
return NSOrderedAscending;
}];
NSLog(@"降序%@",tArray.description);
2.升序
NSArray *tMlist = @[@1,@5,@2,@6,@3,@7,@9];
NSArray *tArray = [tMlist sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
NSNumber *tNumber1 = (NSNumber *)obj1;
NSNumber *tNumber2 = (NSNumber *)obj2;
// 因为满足sortedArrayUsingComparator方法的默认排序顺序,则不需要交换
if ([tNumber1 integerValue] < [tNumber2 integerValue]) return NSOrderedAscending;
return NSOrderedDescending;
}];
NSLog(@"升序%@",tArray.description);
3.数组逆转
NSArray *tMlist = @[@1,@5,@2,@6,@3,@7,@9];
NSArray *tArray = [tMlist sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2){
// 数组逆转
return NSOrderedDescending;
}];
NSLog(@"数组逆转%@",tArray.description);
4.数组不变
NSArray *tMlist = @[@1,@5,@2,@6,@3,@7,@9];
NSArray *tArray = [tMlist sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2){
// 数组不变
return NSOrderedAscending;
}];
NSLog(@"数组不变%@",tArray.description);
网友评论