NSMutableArray排序方式

- (void)sortNSNumberArray{
    //数组元素为NSNumber型
    NSMutableArray *unsortedArray = [NSMutableArray arrayWithObjects:
                           [NSNumber numberWithInt:0],
                           [NSNumber numberWithInt:3],
                           [NSNumber numberWithInt:2],
                           [NSNumber numberWithInt:1],
                           [NSNumber numberWithInt:7],
                           [NSNumber numberWithInt:8],
                           [NSNumber numberWithInt:9],
                           [NSNumber numberWithInt:10],
                           [NSNumber numberWithInt:6],
                           [NSNumber numberWithInt:5],
                           [NSNumber numberWithInt:4],
                           nil];
    // 升序
    // 0 --> 10
    [unsortedArray sortUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        return [obj1 intValue] > [obj2 intValue];
    }];
    NSLog(@"%@", unsortedArray);
    
    // 降序
    // 10 --> 0
    [unsortedArray sortUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        return [obj1 intValue] < [obj2 intValue];
    }];
    NSLog(@"%@", [unsortedArray debugDescription]);
}

- (void)sortStringArray{
    //数组元素为字符串
    NSMutableArray *unsortedArray = [NSMutableArray arrayWithObjects:@"C", @"A", @"H", @"I", @"B", @"D", @"J", @"E", @"F", @"G", @"K", nil];
    // 升序
    // A --> K
    [unsortedArray sortUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        NSString *str1=(NSString *)obj1;
        NSString *str2=(NSString *)obj2;
        return [str1 compare:str2];
    }];
    NSLog(@"%@", [unsortedArray debugDescription]);
    
    // 降序
    // K --> A
    [unsortedArray sortUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        NSString *str1=(NSString *)obj1;
        NSString *str2=(NSString *)obj2;
        return [str2 compare:str1];
    }];
    NSLog(@"%@", [unsortedArray debugDescription]);
}

你可能感兴趣的:(NSMutableArray排序方式)