需求描述:一个数据源集合中含有多个对象(model),对象里含有多个业务属性字段比如价格,时间戳等。现在需要对集合里所有的对象进行价格1.从低到高的排序2.时间从近到远排序。
苹果官方有提供便利的排序NSSortDescriptor
Model *m1 = [Model new];
m1.price = 101;
m1.time= @"2020-10-01";
Model *m2 = [Model new];
m2.price = 100;
m2.time= @"2020-10-02";
Model *m3 = [Model new];
m3.price = 101;
m3.time= @"2020-10-02";
NSMutableArray *array = [NSMutableArray arrayWithObjects:m1,m2,m3, nil];
NSLog(@"---begin%@\n",array);
NSSortDescriptor *priceSort = [[NSSortDescriptor alloc]initWithKey:@"price" ascending:YES];
NSSortDescriptor *timeSort = [[NSSortDescriptor alloc]initWithKey:@"time" ascending:YES];
[array sortUsingDescriptors:@[priceSort,timeSort]];
NSLog(@"---end%@\n",array);
排序前
image.png
排序后价格低->高在价格的基础上在按照时间近->进行排序
image.png
NSSortDescriptor *Sort = [[NSSortDescriptor alloc]initWithKey:@"key" ascending:(BOOL)ascending];
key 是对象里的属性,如果找不到属性会crash,ascending是否为升序排序.多个条件排序可累加。
网友评论