OC数组排序

2019-06-24  本文已影响0人  coming_168

1.定义一组数字数组

NSArray *arr = @[@"12", @"19", @"51", @"86", @"26", @"90"];

2.排序

方法一:

    /** 升序 */
    NSArray *result1 = [arr sortedArrayUsingSelector:@selector(compare:)];
    NSLog(@"result1------%@", result1);
    /** 降序 */ 
    // 将result1数组反向排序
    NSEnumerator *enumerator = [result1 reverseObjectEnumerator];
    NSArray *result2 = [[NSMutableArray alloc] initWithArray:[enumerator allObjects]];
    NSLog(@"result2------%@", result2);

方法二:

    /** 升序 */
    NSArray *result3 = [arr sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        return [obj1 compare:obj2]; //升序排列
    }];
    NSLog(@"result3------%@", result3);
    /** 降序 */ 
    NSArray *result4 = [arr sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        return [obj2 compare:obj1]; //降序排列
    }];
    NSLog(@"result4------%@", result4);

3.打印结果:

result1------(
    12,
    19,
    26,
    51,
    86,
    90
)
result2------(
    90,
    86,
    51,
    26,
    19,
    12
)
result3------(
    12,
    19,
    26,
    51,
    86,
    90
)
result4------(
    90,
    86,
    51,
    26,
    19,
    12
)
上一篇下一篇

猜你喜欢

热点阅读