iOS - NSComparisonResult類與NSComparator類

圖片源于網(wǎng)絡(luò)
NSComparisonResult類:枚舉類型, 來標示比較操作的升降序。其定義如下
typedef NS_ENUM(NSInteger, NSComparisonResult) {NSOrderedAscending = -1L, NSOrderedSame, NSOrderedDescending};

參數(shù)解釋

  • 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); 

參數(shù)解釋

  • id obj1 與 id obj2
    • 將要做比較的對象。
  • block
    • 返回的結(jié)果為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;
}];
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。