数组排序 sortUsingDescriptors:等

- (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;
    }
)

结论:利用排序描述符进行排序。

参考链接:https://www.jianshu.com/p/2e09f9d30a40

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容