1 #pragma mark -- 數組排序方法(升序) 2 3 - (void)arraySortASC{ 4 5 //數組排序 6 7 //定義一個數字數組 8 9 NSArray *array = @[@(3),@(4),@(2),@(1)]; 10 11 //對數組進行排序 12 13 NSArray *result = [array sortedArrayUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) { 14 15 NSLog(@"%@~%@",obj1,obj2); //3~4 2~1 3~1 3~2 16 17 return [obj1 compare:obj2]; //升序 18 19 }]; 20 21 NSLog(@"result=%@",result); 22 23 } 24 25 26 27 #pragma mark -- 數組排序方法(降序) 28 29 - (void)arraySortDESC{ 30 31 //數組排序 32 33 //定義一個數字數組 34 35 NSArray *array = @[@(3),@(4),@(2),@(1)]; 36 37 //對數組進行排序 38 39 NSArray *result = [array sortedArrayUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) { 40 41 NSLog(@"%@~%@",obj1,obj2); //3~4 2~1 3~1 3~2 42 43 return [obj2 compare:obj1]; //降序 44 45 }]; 46 47 NSLog(@"result=%@",result); 48 49 } 50 51 52 53 #pragma mark -- 數組排序方法(亂序) 54 55 - (void)arraySortBreak{ 56 57 //數組排序 58 59 //定義一個數字數組 60 61 NSArray *array = @[@(3),@(4),@(2),@(1),@(5),@(6),@(0)]; 62 63 //對數組進行排序 64 65 NSArray *result = [array sortedArrayUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) { 66 67 NSLog(@"%@~%@",obj1,obj2); 68 69 //亂序 70 71 if (arc4random_uniform(2) == 0) { 72 73 return [obj2 compare:obj1]; //降序 74 75 } 76 77 else{ 78 79 return [obj1 compare:obj2]; //升序 80 81 } 82 83 }]; 84 85 NSLog(@"result=%@",result); 86 87 } 88 89
