对一个模型数组排序

value或者sortValue,都必须是数值类型,否则排序可能不准确

couponArray数组里面存放的都是模型model

NSMutableArray *a = [couponArray sortedArrayUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) {
                BC_MyCouponsModel *mode1 = obj1;
                BC_MyCouponsModel *mode2 = obj2;
                //降序,key表示比较的关键字
                if ([mode1.value floatValue] < [mode2.value floatValue]) {
                    return NSOrderedDescending;
                } else {
                    return NSOrderedAscending;
                }
            }].mutableCopy;

/// 使用NSDescriptor排序 ascending: NO,代表降序,YES代表升序
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"sortValue" ascending:NO];
NSArray *sortPackageResListArr = [couponArray sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];
NSLog(@"%@",sortPackageResListArr);

二. 使用NSDescriptor排序

单个关键字排序

NSMutableArray *array = [NSMutableArray array];    
NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"key" ascending:YES];
[array sortUsingDescriptors:[NSArray arrayWithObject:sort]]; 

多个关键字排序

NSMutableArray *array = [NSMutableArray array];  
NSSortDescriptor *sort1 = [NSSortDescriptor sortDescriptorWithKey:@"key1" ascending:YES];  
NSSortDescriptor *sort2 = [NSSortDescriptor sortDescriptorWithKey:@"key2" ascending:NO]; 
......   
[array sortUsingDescriptors:[NSArray arrayWithObjects:sort1, sort2, nil]];

你可能感兴趣的:(对一个模型数组排序)