zoukankan      html  css  js  c++  java
  • 复杂对象数组的排序

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

    (以字典数组为例)

    (注: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对应对象中的成员变量名。

  • 相关阅读:
    程序相关概念
    C/C++程序语言概念
    详解QT5.10.0搭载OpenCV3.4.0环境配置步骤说明
    微信小程序支付结果 c#后台回调
    信小程序支付(C#后台+前台)
    微信小程序知识集锦
    WPF获取读取电脑指定文件夹中的指定文件的地址
    WPF后台动画DoubleAnimation讲解
    wpf datagrid 的单元格内容超出列宽度
    WPF实现3D翻转的动画效果
  • 原文地址:https://www.cnblogs.com/ranger-jlu/p/3884422.html
Copyright © 2011-2022 走看看