- (void)sortUsingDescriptors:(NSArray<NSSortDescriptor *> *)sortDescriptors;
该方法的作用就是:利用给定的排序描述符,对对象进行排序。
- (instancetype)sortDescriptorWithKey:(nullable NSString *)key ascending:(BOOL)ascending
- (instancetype)initWithKey:(nullable NSString *)key ascending:(BOOL)ascending
key : 排序key, 某个对象的属性名称; 如果对字符串进行排序, 则传nil
ascending : 是否升序, YES-升序, NO-降序
看一下参数
sortDescriptors:包含用于对接收数组的内容进行排序的NSSortDescriptor对象的数组。
看示例代码
- (void)demoSortDescription
{
NSDictionary *dic1 = [NSDictionary dictionaryWithObjectsAndKeys:@"2030",@"year", @"1",@"month",nil];
NSDictionary *dic2 = [NSDictionary dictionaryWithObjectsAndKeys:@"2010",@"year", @"2",@"month", nil];
NSDictionary *dic3 = [NSDictionary dictionaryWithObjectsAndKeys:@"2050",@"year", @"3",@"month" ,nil];
NSDictionary *dic4 = [NSDictionary dictionaryWithObjectsAndKeys:@"2014",@"year", @"4",@"month",nil];
NSDictionary *dic5 = [NSDictionary dictionaryWithObjectsAndKeys:@"2050",@"year", @"4",@"month",nil];
NSMutableArray *arrM = [NSMutableArray arrayWithObjects:dic1, dic2, dic3, dic4, dic5, nil];
NSSortDescriptor *descripor = [NSSortDescriptor sortDescriptorWithKey:@"year" ascending:YES];
NSSortDescriptor *descripor2 = [NSSortDescriptor sortDescriptorWithKey:@"month" ascending:YES];
[arrM sortUsingDescriptors:[NSArray arrayWithObjects:descripor, descripor2, nil]];//先按第一个来拍,再按第二个来拍
NSLog(@"resultArr = %@", arrM);
}
看输出结果
2017-08-26 23:51:46.047 JJOC[18488:495473] resultArr = (
{
month = 2;
year = 2010;
},
{
month = 4;
year = 2014;
},
{
month = 1;
year = 2030;
},
{
month = 3;
year = 2050;
},
{
month = 4;
year = 2050;
}
)
结论:利用排序描述符进行排序。