• 复杂对象数组的排序


     开发中经常需要对数据进行排序再使用,排序的数组往往是较复杂的对象,比如字典、自定义类型等,对这一类数组的排序方法如下:

    (以字典数组为例)

    (注:result为待排序数组,newResult为排序后的数组)

     

    1、排序参考为数字

    NSArray *newResult =

            [result sortedArrayUsingComparator:^(id obj1,id obj2)

            {

                NSDictionary *dic1 = (NSDictionary *)obj1;

                NSDictionary *dic2 = (NSDictionary *)obj2;

                NSNumber *num1 = (NSNumber *)[dic1 objectForKey:@"value"];

                NSNumber *num2 = (NSNumber *)[dic2 objectForKey:@"value"];

                if ([num1 floatValue] > [num2 floatValue])

                {

                    return (NSComparisonResult)NSOrderedAscending;

                }

                else

                {

                    return (NSComparisonResult)NSOrderedDescending;

                }

                return (NSComparisonResult)NSOrderedSame;

            }];

     

    2、排序参考为字符串

     

    NSArray *newResult =

     

        [result sortedArrayUsingComparator:^(id obj1,id obj2)

     

         {

     

             NSDictionary *dic1 = ((SHPlot *)obj1).plotThemeAttributes;

     

             NSDictionary *dic2 = ((SHPlot *)obj2).plotThemeAttributes;

     

             NSString *version1 = (NSString *)[dic1 objectForKey:@"version"];

     

             NSString *version2 = (NSString *)[dic2 objectForKey:@"version"];

     

             

     

             return [version1 compare:version2 options:NSLiteralSearch];

     

         }];

     

    近期,同事推荐使用NSDescriptor对复杂对象数组进行排序进,尝试了一下确实也不错。

    使用NSDescriptor进行排序

    NSSortDescriptor不仅可以用来对数组进行排序,还能指定element在table view中的排序,以及Core Data中对fetch request返回的数据做排序处理。通过NSSortDescriptor可以很方便的对数组进行多个key的排序。下面来看看如何对我们的数组做surname排序,然后在进行name排序:

    1
    2
    3
    4
    5
    6
    
    NSSortDescriptor *firstDescriptor = [[NSSortDescriptor alloc] initWithKey:@"surname" ascending:YES];
    NSSortDescriptor *secondDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
    
    NSArray *sortDescriptors = [NSArray arrayWithObjects:firstDescriptor, secondDescriptor, nil];
    
    NSArray *sortedArray = [self.persons sortedArrayUsingDescriptors:sortDescriptors];

    其中,surname和name对应对象中的成员变量名。

  • 相关阅读:
    35.python之事件驱动模型
    33.python之操作系统,进程,线程
    VRChat之blender2.8版本设置
    VRChat模型制作及上传总篇(201912)
    linux常用指令
    java基础File的简单使用记录
    java 通过实现Comparable接口使用Collections.sort排序 及 利用set的特性对 list 进行去重
    [转发] java字符串-编码转换-工具类
    ssh服务不能远程时,使用telnet远程登录
    java中List遍历删除元素相关做法和注意事项
  • 原文地址:https://www.cnblogs.com/ranger-jlu/p/3884422.html
Copyright © 2020-2023  润新知