1

让我有未排序的NSMutableDictionary

    {
        A = "3";
        B = "2"; 
        C = "4";
    }

我需要结果是这样的:

    {
        B = "2";
        A = "3";
        C = "4";
    }

我怎样才能在目标 c中实现这一结果。

一个简单的代码实现将不胜感激。

4

5 回答 5

7

NSMutableDictionary 不可能,它不是排序结构。您必须将其转换为 NSArray,然后对其进行排序。然后,您将没有字典结构。

于 2012-09-28T12:43:02.623 回答
3

您不能将NSMutableDictionary按值排序为@joe 和@mavrick3 答案。但是,如果您将那里的键和值更改为NSArray,您可以做到。这是简单的实现。 NSMutableDictionary *results; //要排序的字典

    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]); 
    }
于 2012-09-28T12:54:30.127 回答
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);
于 2012-09-28T14:31:56.987 回答
0

NSDictionaryNSMutableDictionary不能按值排序。您只能使用 aNSArray对它们进行排序。但是您必须使用自己的代码来完成此操作,并且您不会获得与您想要的相同的输出。

于 2012-09-28T12:47:01.860 回答
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);
于 2012-09-28T12:52:09.223 回答