首页 > 代码库 > 用block变量来对字符数组对象进行排序

用block变量来对字符数组对象进行排序

<span style="font-size:18px;">降序排序</span>
<span style="font-size:18px;">NSMutableArray *arr = [NSMutableArray arrayWithObjects:@"abc",@"bcd",@"123",@"9987", nil];
        
        NSComparisonResult (^block)(NSString *str1, NSString *str2) = ^(NSString *str1, NSString *str2){
            return -[str1 compare:str2];
        };
        NSArray *arr1 =[arr sortedArrayUsingComparator:block];
        NSLog(@"%@",arr1);
</span>
<span style="font-size:18px;">升序排序</span>

NSMutableArray *arr = [NSMutableArray arrayWithObjects:@"abc",@"bcd",@"123",@"9987", nil]; NSComparisonResult (^block)(NSString *str1, NSString *str2) = ^(NSString *str1, NSString *str2){ return [str1 compare:str2]; };  

NSArray *arr1 =[arr sortedArrayUsingComparator:block];  

NSLog(@"%@",arr1);