问题描述
- 升序排列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中存在的值。
解决方案
不知道你的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) {
......
}
时间: 2024-12-22 00:02:45