?需求描述:一個數(shù)據(jù)源集合中含有多個對象(model),對象里含有多個業(yè)務(wù)屬性字段比如價格炎功,時間戳等∶度撸現(xiàn)在需要對集合里所有的對象進(jìn)行價格1.從低到高的排序2.時間從近到遠(yuǎn)排序。
蘋果官方有提供便利的排序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);
排序前
排序后價格低->高在價格的基礎(chǔ)上在按照時間近->進(jìn)行排序
NSSortDescriptor *Sort = [[NSSortDescriptor alloc]initWithKey:@"key" ascending:(BOOL)ascending];
key 是對象里的屬性蛇损,如果找不到屬性會crash赁温,ascending是否為升序排序.多個條件排序可累加。