按升序对NSDictionary进行sorting

我想按升序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" ) 

NSSortedDescriptor 在这里有一篇很好的文章。

尝试使用这一个….

// 变化…….

 NSArray *valDict = [[self.mGetDataDict allValues] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)]; NSMutableDictionary *orderedDictionary=[[NSMutableDictionary alloc] init]; for (NSString *valor in valDict) { for (NSString *clave in [yourDictionary allKeys]) { if ([valor isEqualToString:[valDict valueForKey:clave]]) { [orderedDictionary setValue:valor forKey:clave]; } } } 

获取值的数组,sorting该数组,然后获取与该值相对应的键。

您可以通过以下方式获取值:

 NSArray* values = [myDict allValues]; NSArray* sortedValues = [values sortedArrayUsingSelector:@selector(comparator)]; 

但是,如果集合如您在示例中所示(我的意思是,您可以从关键字中推断出该值),则始终可以对关键字进行sorting,而不是对这些值进行调整。

使用:

 NSArray* sortedKeys = [myDict keysSortedByValueUsingSelector:@selector(comparator)]; 

比较器是一个消息select器,它被发送到您要订购的对象。

如果你想要命令string,那么你应该使用一个NSString比较器。 NSString比较器是ie:caseInsensitiveCompare或localizedCaseInsensitiveCompare :.

如果这些都不适用于您,您可以调用您自己的比较器function

 [values sortedArrayUsingFunction:comparatorFunction context:nil] 

正在比较函数 (来自AppleDocumentation )

 NSInteger intSort(id num1, id num2, void *context) { int v1 = [num1 intValue]; int v2 = [num2 intValue]; if (v1 < v2) return NSOrderedAscending; else if (v1 > v2) return NSOrderedDescending; else return NSOrderedSame; }