iOS - NSComparisonResult类与NSComparator类

图片源于网络
NSComparisonResult类:枚举类型, 来标示比较操作的升降序。其定义如下
typedef NS_ENUM(NSInteger, NSComparisonResult) {NSOrderedAscending = -1L, NSOrderedSame, NSOrderedDescending};

参数解释

  • 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.(左边的操作对象大于右边的对象)
NSComparator类:实际上是用一个block对象作比较操作(The arguments to the Block object are two objects to compare. The block returns an NSComparisonResult value to denote the ordering of the two objects)。其定义如下:
typedef NSComparisonResult (^NSComparator)(id obj1, id obj2); 

参数解释

  • id obj1 与 id obj2
    • 将要做比较的对象。
  • block
    • 返回的结果为NSComparisonResult类型来表示两个对象的顺序

使用范例:

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;
}];