美文网首页
对一个模型数组排序

对一个模型数组排序

作者: eryuxinling | 来源:发表于2020-05-09 09:54 被阅读0次
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]];

相关文章

网友评论

      本文标题:对一个模型数组排序

      本文链接:https://www.haomeiwen.com/subject/nvyhnhtx.html