【问题标题】:Sorting NSArray of dictionaries by value of a key in the dictionaries按字典中键的值对字典的 NSArray 进行排序
【发布时间】:2012-03-19 12:43:32
【问题描述】:

我有一个由字典填充的数组,我需要按字典的其中一个键的值按字母顺序对数组进行排序。

这是我的数组:

tu dictus: (
    {
    brand = Ryul;
    productTitle = Any;
    quantity = 1;
    subBrand = "Ryul INJ";
    type = Product;
},
    {
    brand = Trol;
    productTitle = Different;
    quantity = 2;
    subBrand = "";
    type = Brand;
},
    {
    brand = Dtor;
    productTitle = Any;
    quantity = 1;
    subBrand = "";
    type = Product;
},
    {
    brand = Ryul;
    productTitle = Different;
    quantity = 2;
    subBrand = "Ryul CHES";
    type = SubBrand;
},
    {
    brand = Anan;
    productTitle = Any;
    quantity = 1;
    subBrand = "";
    type = Product;
}
)

通常我会使用对数组进行排序

myArray = [uniqueProdsArray sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];

但是如何使用字典的brand 键进行排序呢?

【问题讨论】:

标签: ios objective-c sorting nsarray nsdictionary


【解决方案1】:

我认为这样做可以:

brandDescriptor = [[NSSortDescriptor alloc] initWithKey:@"brand" ascending:YES];
sortDescriptors = [NSArray arrayWithObject:brandDescriptor];
sortedArray = [myArray sortedArrayUsingDescriptors:sortDescriptors];

我从Sort Descriptor Programming Topics 中提取了代码。此外,Key-Value Coding 发挥作用,因为sortedArrayUsingDescriptors: 将向myArray 中的每个元素发送valueForKey:,然后使用标准比较器对返回的值进行排序。

【讨论】:

  • 如何在 swift2 中使用这个?
【解决方案2】:

将此用于 swift 4

let sortedArray = arrayTobeSort.sorted {$0["keyName"].compare($1["keyName"]) == ComparisonResult.orderedAscending}

您也可以使用 ComparisonResult.orderedDescending 进行降序排序

【讨论】:

    【解决方案3】:

    我的代码在使用NSSortDescriptor 时崩溃了,所以最终使用了一个在我的用例中效果很好的块,我希望“等级”是一个 NSNumber。如果对象不能转换为整数,它不会排序,但也不会导致崩溃。

    NSArray *sortedArray = [data sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        long data1 = [[obj1 valueForKey:@"rank"] integerValue];
        long data2 = [[obj2 valueForKey:@"rank"] integerValue];
        if (data1 > data2) {
            return (NSComparisonResult)NSOrderedDescending;
        }
        if (data1 < data2) {
            return (NSComparisonResult)NSOrderedAscending;
        }
        return (NSComparisonResult)NSOrderedSame;
    }];
    

    【讨论】:

      【解决方案4】:

      试试最简单的方法...

      myArray = [[NSMutableArray alloc] init];
      NSMutableArray *tempArray = [[NSMutableArray alloc] init];
      [tempArray removeAllObjects];
      [tempArray addObjectsFromArray: myArray];
      
      NSString *key = @"brand";
      NSSortDescriptor *brandDescriptor = [[NSSortDescriptor alloc] initWithKey:key ascending:YES];
      NSArray *sortDescriptors = [NSArray arrayWithObjects:brandDescriptor,nil];
      NSArray *sortedArray = [tempArray sortedArrayUsingDescriptors:sortDescriptors];
      [brandDescriptor release];
      [tempArray removeAllObjects];
      tempArray = (NSMutableArray*)sortedArray;
      [myArray removeAllObjects];
      [myArray addObjectsFromArray:tempArray];
      

      【讨论】:

        【解决方案5】:

        你可以这样做。

        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"d LLLL yyyy"];
        
        NSComparator compareDates = ^(id string1, id string2)
        {
            NSDate *date1 = [formatter dateFromString:string1];
            NSDate *date2 = [formatter dateFromString:string2];
        
            return [date1 compare:date2];
        };
        NSSortDescriptor * sortDesc1 = [[NSSortDescriptor alloc] initWithKey:@"date" ascending:NO comparator:compareDates];
        [array sortUsingDescriptors:[NSArray arrayWithObjects:sortDesc1, nil]];
        

        【讨论】:

          【解决方案6】:

          使用以下代码使用字典中的“品牌”键进行排序..

          NSSortDescriptor * brandDescriptor = [[NSSortDescriptor alloc] initWithKey:@"brand" ascending:YES];
          NSArray * sortDescriptors = [NSArray arrayWithObject:brandDescriptor];
          NSArray * sortedArray = [myArray sortedArrayUsingDescriptors:sortDescriptors];
          NSLog(@"sortedArray %@",sortedArray);
          

          使用以下代码,如果您要根据字典中的两个键进行排序;比如,字典中的“品牌”键和产品标题键:-

          NSSortDescriptor * brandDescriptor = [[NSSortDescriptor alloc] initWithKey:@"brand" ascending:YES];
          NSSortDescriptor * productTitleDescriptor = [[NSSortDescriptor alloc] initWithKey:@"productTitle" ascending:YES];
          NSArray * sortDescriptors = [NSArray arrayWithObjects:brandDescriptor, productTitleDescriptor, nil];
          NSArray * sortedArray = [feedData sortedArrayUsingDescriptors:sortDescriptors];
          NSLog(@"sortedArray %@",sortedArray);
          

          【讨论】:

            【解决方案7】:

            在 switf 中:

            var descriptor: NSSortDescriptor = NSSortDescriptor(key: "brand", ascending: true)
            var sortedResults: NSArray = results.sortedArrayUsingDescriptors([descriptor])
            

            【讨论】:

              【解决方案8】:

              作为 QED 代码的补充,

              NSSortDescriptor * brandDescriptor = [[NSSortDescriptor alloc] initWithKey:@"brand" ascending:YES];
              NSArray * sortedArray = [myArray sortedArrayUsingDescriptors:@[brandDescriptor]];
              

              这明确了变量的类别并通过快速枚举优化了数组创建。 谢谢

              【讨论】:

                【解决方案9】:
                 arrSorted = [arrBrand sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
                            if ([[obj1 valueForKey:@"iUserId"] integerValue] > [[obj2 valueForKey:@"iUserId"] integerValue]) {
                                return (NSComparisonResult)NSOrderedDescending;
                            }
                            if ([[obj1 valueForKey:@"iUserId"] integerValue] < [[obj2 valueForKey:@"iUserId"] integerValue]) {
                                return (NSComparisonResult)NSOrderedAscending;
                            }
                            return (NSComparisonResult)NSOrderedSame;
                        }];
                

                【讨论】:

                • 虽然 sortedArrayUsingComparator 是可行的方法,但最多可以调用四次“valueForKey”而不是两次调用“objectForKey”是不好的。顺便提一句。由于您需要字典,因此请使用 NSDictionary* 作为类型,而不是 id。
                【解决方案10】:
                NSSortDescriptor *brandDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"Position" ascending:YES selector:@selector(localizedStandardCompare:)] autorelease];
                      NSArray *sortDescriptors = [NSArray arrayWithObject:brandDescriptor];
                      NSArray  *sortedArray = [arrTemp sortedArrayUsingDescriptors:sortDescriptors];
                     array_PreLagData=(NSMutableArray*)sortedArray;
                
                unsorted array
                Printing description of arrTemp:
                <__NSArrayM 0x10282100>(
                {
                    Milker2 = "11:03:17 AM";
                    Position = 2;
                },
                {
                    Milker1 = "11:03:28 AM";
                    Position = 25;
                },
                {
                    Milker3 = "11:03:18 AM";
                    Position = 3;
                },
                {
                    Milker1 = "11:03:16 AM";
                    Position = 1;
                    Strip = "11:32:32 AM";
                },
                {
                    Milker1 = "11:03:21 AM";
                    Position = 10;
                }
                )
                Sorted array
                <__NSArrayI 0x101363c0>(
                {
                    Milker1 = "11:03:16 AM";
                    Position = 1;
                    Strip = "11:32:32 AM";
                },
                {
                    Milker2 = "11:03:17 AM";
                    Position = 2;
                },
                {
                    Milker3 = "11:03:18 AM";
                    Position = 3;
                },
                {
                    Milker1 = "11:03:21 AM";
                    Position = 10;
                },
                {
                    Milker1 = "11:03:28 AM";
                    Position = 25;
                }
                )
                
                [enter link description here][1]
                
                
                  [1]: https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/SortDescriptors/Articles/Creating.html#//apple_ref/doc/uid/20001845-BAJEAIEE
                

                【讨论】:

                  【解决方案11】:

                  我们通过使用以下方法得到了解决方案

                  [self.jsonData sortUsingDescriptors: [NSArray arrayWithObjects: [NSSortDescriptor sortDescriptorWithKey:"fullname" ascending:YES], [NSSortDescriptor sortDescriptorWithKey:"id" ascending:NO], nil]];
                  

                  地点:-

                  jsonData - MutableArray 保存已解析的 JSON 数据。

                  fullname - 我们要排序的数据。

                  id - 内部字典附带的唯一数据。

                  【讨论】:

                    猜你喜欢
                    • 2015-07-15
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 2011-07-08
                    • 2019-01-25
                    • 1970-01-01
                    相关资源
                    最近更新 更多