对模型数组进行排序
2022-02-23 本文已影响0人
梁森的简书
代码
NSMutableArray <PersonModel *>*mutableArr = [NSMutableArray array];
NSArray *scores = @[@(10), @(50), @(90), @(60)];
for (NSInteger i = 0; i < scores.count; i ++) {
PersonModel *p = [[PersonModel alloc] init];
p.score = [scores[i] floatValue];
[mutableArr addObject:p];
}
static BOOL asc = NO;
asc = !asc;
if (asc) {
NSLog(@"升序");
} else {
NSLog(@"降序");
}
NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"score" ascending:asc];
NSArray <PersonModel *>*sortedArr = [mutableArr sortedArrayUsingDescriptors:@[sort]];
[sortedArr enumerateObjectsUsingBlock:^(PersonModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
NSLog(@"score:%lf", obj.score);
}];
疑问:如何更优雅地对模型数组进行排序?
排序的key可能是动态变化的,而我又不想使用这种硬编码(@"score")的方式,该怎么办?