2 for 2012 for_2012 于 2013.06.05 14:19 提问

升序排列NSDictionary

要升序排列一个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中存在的值。

1个回答

zhanglei5415
zhanglei5415   Rxr 2013.06.06 14:21

不知道你的json是什么样的格式.是如下这种吗?

{"1":"off","10":"off","2":"on", "3":"on"}

如果是.且我们看到key是整型的话,你可以这样比较来拿到正确的排序结果

NSArray *sortKeys=[[valDict allKeys] sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        return [obj1 intValue] > [obj2 intValue];
}];

NSLog(@"sort key:%@",sortKeys);
for (NSString *valueKey in sortKeys) {
    ......
}
Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!