sortedArrayUsingComparator

1.降序
NSArray *tMlist = @[@4,@5,@2,@6,@3,@7,@8]; //降序序8,7,。。 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; //因为满足sortedArrayUsingComparator方法的默认排序顺序,则不需要交换 if ([tNumber1 integerValue] > [tNumber2 integerValue]) return NSOrderedAscending; return NSOrderedDescending;
2 升序
NSArray *tMlist = @[@4,@5,@2,@6,@3,@7,@8]; //结果:升序2,4,。。 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; // 因为不满足sortedArrayUsingComparator方法的默认排序顺序,则需要交换。 // if ([tNumber1 integerValue] < [tNumber2 integerValue]) // return NSOrderedAscending ; // return NSOrderedDescending; }];
3 数组逆转
NSArray *tMlist = @[@4,@5,@2,@6,@3,@7,@8]; NSArray *tArray = [tMlist sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) { NSNumber *tNumber1 = (NSNumber *)obj1; NSNumber *tNumber2 = (NSNumber *)obj2; //数组逆转 return NSOrderedDescending; }];
4.数组不变
NSArray *tMlist = @[@4,@5,@2,@6,@3,@7,@8]; NSArray *tArray = [tMlist sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) { NSNumber *tNumber1 = (NSNumber *)obj1; NSNumber *tNumber2 = (NSNumber *)obj2; //数组不变 return NSOrderedAscending; }];

总结:
1.sortedArrayUsingComparator这个方法本身就是按递增的方式排序。2.返回的返回值(NSOrderedAscending 不交换,NSOrderedSame 不交换,NSOrderedDescending 交换)。例如:object1 < object2 返回:NSOrderedDescending 则交换(变为object2,object1),以保证安方法本身升序。返回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)。

你可能感兴趣的:(sortedArrayUsingComparator)