NSMutableArray的双条件或多条件排序

时间:2021-05-11 02:54:07

最近我在研究双条件或多条件排序,当然是有主要条件和次要条件的咯。假设有这么个场景:需要对优惠卷进行双重条件排序,根据优惠卷状态和优惠卷的消费金额进行正序排序,所用代码如下:

先按照优惠卷状态排序,状态一样再按优惠卷消费金额排序.

初级方法:

- (void)sortArr {

    NSMutableArray *customArr = [[NSMutableArrayalloc] init];

    for (NSInteger i =0 ; i < 100; i ++) {

        CustomMode *mode = [[CustomModealloc] init];

        mode.customName = [NSStringstringWithFormat:@"客户%ld",(long)i];

        mode.couponCode = [selfarcdomStr];

        mode.couponPrice = arc4random()%8888 + 1;

        mode.consumeStatus =arc4random()%ConsumeStatus_noRejected;

        [customArr addObject:mode];

    }

    

    NSArray *sortArr =  [customArr sortedArrayUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) {

        CustomMode *mode1 = (CustomMode *)obj1;

        CustomMode *mode2 = (CustomMode *)obj2;

        [@(mode1.consumeStatus)compare:@(mode2.consumeStatus)];

        if (mode1.consumeStatus > mode2.consumeStatus) {

            returnNSOrderedDescending;

        } else if (mode1.consumeStatus == mode2.consumeStatus) {

            return (mode1.couponPrice > mode2.couponPrice);

        } else if (mode1.consumeStatus < mode2.consumeStatus) {

            returnNSOrderedAscending;

        }

        return NSOrderedSame;

    }];

    

    for (CustomMode *modein sortArr) {

        NSLog(@"consumeStatus is %d couponPrice is %f\n\n",mode.consumeStatus,mode.couponPrice);

    }

}

高级方法:

- (void)sortArr1 {

    NSMutableArray *customArr = [[NSMutableArray alloc] init];

    for (NSInteger i = 0 ; i < 100; i ++) {

        CustomMode *mode = [[CustomMode alloc] init];

        mode.customName = [NSString stringWithFormat:@"客户%ld",(long)i];

        mode.couponCode = [self arcdomStr];

        mode.couponPrice = arc4random()%8888 + 1;

        mode.consumeStatus = arc4random()%ConsumeStatus_noRejected;

        [customArr addObject:mode];

    }

    NSDate *date = [NSDate date];

    

    // 1.先按照书名进行排序

    // 这里的key写的是@property的名称

    NSSortDescriptor *statusDesc = [NSSortDescriptor sortDescriptorWithKey:@"consumeStatus" ascending:YES];

    // 2.再按照姓进行排序

    NSSortDescriptor *priceDesc = [NSSortDescriptor sortDescriptorWithKey:@"couponPrice" ascending:YES];

    // 按顺序添加排序描述器

    NSArray *descs = [NSArray arrayWithObjects:statusDesc, priceDesc, nil];

    NSArray *array2 = [customArr sortedArrayUsingDescriptors:descs];

    //        for (CustomMode *mode in array2) {

    //            NSLog(@"\nconsumeStatus is %d couponPrice is %f\n\n",mode.consumeStatus,mode.couponPrice);

    //        }

    NSLog(@"tmv2 is %f",[[NSDate date] timeIntervalSinceDate:date]);

}



代码github地址:https://github.com/songxuhua/TestForAlgorithms