让我有未排序的 NSMutableDictionary
{
A = "3";
B = "2";
C = "4";
}
我需要结果如下:
{
B = "2";
A = "3";
C = "4";
}
如何在目标c 中实现此结果。
一个简单的代码实现将不胜感激。
答案 0 :(得分:7)
NSMutableDictionary不可能,它不是排序结构。您将不得不将其转换为NSArray然后对其进行排序。那么你将没有字典结构。
答案 1 :(得分:3)
您不能将值 NSMutableDictionary 排序为@joe和@mavrick3。但是,如果您将键和值更改为 NSArray ,则可以执行此操作。 这是简单的实现.. NSMutableDictionary *结果; //要排序的字典
NSMutableDictionary *results; //dict to be sorted NSArray *sortedKeys = [results keysSortedByValueUsingComparator: ^(id obj1, id obj2) { if ([obj1 integerValue] > [obj2 integerValue]) return (NSComparisonResult)NSOrderedDescending; if ([obj1 integerValue] < [obj2 integerValue]) return (NSComparisonResult)NSOrderedAscending; return (NSComparisonResult)NSOrderedSame; }]; NSArray *sortedValues = [[results allValues] sortedArrayUsingSelector:@selector(compare:)]; //Descending order for (int s = ([sortedValues count]-1); s >= 0; s--) { NSLog(@" %@ = %@",[sortedKeys objectAtIndex:s],[sortedValues objectAtIndex:s]); } //Ascending order for (int s = 0; s < [sortedValues count]; s++) { NSLog(@" %@ = %@",[sortedKeys objectAtIndex:s],[sortedValues objectAtIndex:s]); }
答案 2 :(得分:1)
您可以尝试按字母排序。
NSMutableDictionary *tmpDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"6",@"A",@"3",@"B",@"5",@"C",@"2",@"D",@"21",@"F",@"20",@"G",nil];
NSArray *sortedArray = [tmpDict keysSortedByValueUsingComparator:^NSComparisonResult(id obj1,id obj2){
return [obj1 compare:obj2 options:NSNumericSearch];
}];
NSLog(@"Sorted = %@",sortedArray);
答案 3 :(得分:0)
NSDictionary
以及NSMutableDictionary
无法按值排序。您只能使用NSArray
对其进行排序。但是你必须使用自己的代码,并且你不会得到你想要的相同输出。
答案 4 :(得分:0)
这是最简单的方法
NSArray *arr = [NSArray arrayWithObjects:@"2", @"4", @"1", nil];
NSArray *sorted = [arr sortedArrayUsingSelector:@selector(compare:)];
NSLog(@"Pre sort : %@", arr);
NSLog(@"After sort : %@", sorted);
如果你有f.ex.字典数组(或模型对象),你可以这样做:
NSDictionary *dict1 = [NSDictionary dictionaryWithObject:@"Mannie" forKey:@"name"];
NSDictionary *dict2 = [NSDictionary dictionaryWithObject:@"Zannie" forKey:@"name"];
NSDictionary *dict3 = [NSDictionary dictionaryWithObject:@"Cannie" forKey:@"name"];
NSArray *peopleIKnow = [NSArray arrayWithObjects:dict1, dict2, dict3, nil];
NSSortDescriptor *sorty = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES];
NSArray *results = [peopleIKnow sortedArrayUsingDescriptors:[NSArray arrayWithObject:sorty]];
NSLog(@"Before : %@", peopleIKnow);
NSLog(@"After : %@", results);