什么是NSComparisonResult和NSComparator???
官方文档:https://developer.apple.com
typedef NS_ENUM(NSInteger, NSComparisonResult)
{
NSOrderedAscending = -1L, //值为-1 代表升序排列
NSOrderedSame, //值为0
NSOrderedDescending //值为1 待变降序排列
};
基础类库中声明了NSComparator块代码类型来进行两个条目的比较:
typedef NSComparisonResult (^NSComparator)(id obj1, id obj2);
NSComparator是一个块代码类型,并且使用两个对象作为参数,返回一个NSComparisonResult类型的值。它是NSSortDescriptor,NSArray, 和NSDictionary等类的方法的参数,用来进行排序.
比较
NSString *a = @"aaaA";//'A'的ASCII码值是65 NSString *b = @"aaaa";//'a'的ASCII码值是97 NSComparisonResult comparisonResult = [a compare:b]; if (comparisonResult == NSOrderedAscending) { NSLog(@"b > a"); } else if (comparisonResult == NSOrderedDescending) { NSLog(@"a > b"); } else if (comparisonResult == NSOrderedSame) { NSLog(@"a = b"); } NSLog(@"comparisonResult = %ld",comparisonResult);
//输出结果为-1,即:NSOrderedAscending。
//表示在两个字符串不相同,且第一个字符所在的字符串a比b的ASCII码值要小。
//比较 NSNumber *num1 = [[NSNumber alloc]initWithFloat:15.5]; NSNumber *num2 = [[NSNumber alloc]initWithFloat:15.5]; NSComparisonResult result = [num1 compare:num2]; if (result == NSOrderedSame) { NSLog(@"a"); } NSLog(@"result = %ld",result);
排序(升序)
NSArray *stringArray = [NSArray arrayWithObjects:@"abc 1", @"abc 21", @"abc 12",@"abc 13",@"abc 05",nil]; NSComparator sortBlock = ^(id string1, id string2) { return [string1 compare:string2]; }; //利用数组的sortedArrayUsingComparator调用 NSComparator ,obj1和obj2指的数组中的对象 NSArray *sortArray = [stringArray sortedArrayUsingComparator:sortBlock]; NSLog(@"sortArray = %@", sortArray); //或者(升序) NSArray *sortArray1 = [stringArray sortedArrayUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) { return [obj1 compare:obj2]; }]; NSLog(@"sortArray1 = %@", sortArray1);
降序
NSArray *numArray = [NSArray arrayWithObjects:@1,@21,@12,@13,@05, nil]; NSArray *sortNumArray = [numArray sortedArrayUsingComparator: ^(id obj1, id obj2) { if ([obj1 integerValue] > [obj2 integerValue]) { return (NSComparisonResult)NSOrderedAscending; } if ([obj1 integerValue] < [obj2 integerValue]) { return (NSComparisonResult)NSOrderedDescending; } return (NSComparisonResult)NSOrderedSame; }]; NSLog(@"sortNumArray = %@",sortNumArray);