本文介绍了按升序排序NSDictionary的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试按升序排序 NSDictionary 。我正在使用此代码:

I am trying to sort an NSDictionary in ascending order. I am using this code:

NSDictionary *valDict = self.mGetDataDict[key][rowKey];

for (NSString *valueKey in
     [[valDict allKeys] sortedArrayUsingSelector:@selector(compare:)])
{
    if ([valueKey isEqualToString:@"attr"])
    {
        dictRow = self.mGetDataDict[key][rowKey][valueKey];
    }
    else {
        NSString *valKey = self.mGetDataDict[key][rowKey][valueKey];
        [arrSeatsStatus addObject:valKey];
    }
}

这是我得到的输出:

1 = off;
10 = off;
2 = on;
3 = on;
4 = on;
5 = on;
6 = on;
7 = on;
8 = on;
9 = on;

这是必需的输出:

1: "off",
2: "on",
3: "on",
4: "on",
5: "on",
6: "on",
7: "on",
8: "on",
9: "on",
10: "off"

所需输出是来自JSON的实际值。

The required output is an actual value coming from JSON.

推荐答案

您可以像这样使用NSSortDescriptor:

You can use NSSortDescriptor like this:

NSArray* array1 = @[@"1 = off", @"10 = off", @"2 = on", @"3 = on"];
NSSortDescriptor *descriptor = [NSSortDescriptor sortDescriptorWithKey:@"" ascending:YES selector:@selector(localizedStandardCompare:)];

NSLog(@"Ordered array: %@", [array1 sortedArrayUsingDescriptors:@[ descriptor ]]);

产生此输出:

2013-06-04 12:26:22.039 EcoverdFira[3693:c07] Ordered array: (
  "1 = off",
  "2 = on",
  "3 = on",
  "10 = off"
)

关于 NSSortedDescriptor 的有一篇很好的文章。

There's a good article on NSSortedDescriptor's here.

这篇关于按升序排序NSDictionary的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-05 10:56