iphone - 按升序对 NSDictionary 进行排序

标签 iphone ios objective-c json sorting

我正在尝试按升序对 NSDictionary 进行排序。我正在使用这段代码:

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 的实际值。

最佳答案

您可以像这样使用 NSSortDescriptor:

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"
)

关于 NSSortedDescriptorhere 有一篇很好的文章.

关于iphone - 按升序对 NSDictionary 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16913847/

相关文章:

iOS App - 为每个新的一天更新字符串数组

ios - NSCoreData 条目获取的性能

objective-c - 以编程方式滚动 UIScrollView

iphone - 检测NSString是否包含中文字符

ios - 将矩形图像比例缩放为适合正方形的比例,以与MPMediaItemArtwork一起使用

iphone - 如何只加载网页的主体

iphone - 2 CSS Media Query 定义是否可以重叠

ios - 我如何避免 IOS Storyboard segue 循环

ios - 在 ios 的 UIWebview 中调用 javaScript

iphone - 在方向更改期间使用 drawRect 拉伸(stretch)