13

好的,所以我知道字典无法排序。但是,假设我NSMutableArray *keys = [someDictionary allKeys];现在,我想根据字典中的相应值(按字母顺序)对这些键进行排序。因此,如果字典包含key=someString,那么我想keys根据它们对应的字符串进行排序。我认为它的一些应用,sortUsingComparator但在这一点上它有点超出我的能力范围。

4

5 回答 5

21
NSArray *keys = [someDictionary allKeys];
NSArray *sortedKeys = [keys sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
    NSString *first = [someDictionary objectForKey:a];
    NSString *second = [someDictionary objectForKey:b];
    return [first compare:second];
}];
于 2012-07-19T06:16:25.557 回答
3
NSDictionary *dict = // however you obtain the dictionary
NSMutableArray *sortedKeys = [NSMutableArray array];

NSArray *objs = [dict allValues];
NSArray *sortedObjs = [objs sortedArrayUsingSelector:@selector(compare:)];
for (NSString *s in sortedObjs)
    [sortedKeys addObjectsFromArray:[dict allKeysForObject:s]];

现在sortedKey将包含按其对应对象排序的键。

于 2012-07-19T06:13:13.243 回答
3

NSDictionary 基于字典键的排序

Abobe 用于返回基于字典内容的排序数组,这是用于返回按字典键排序的数组:

NSArray *keys = [theDictionary allKeys];
NSArray *sortedKeys = [keys sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
    return [a compare:b];
}];
NSMutableArray *sortedValues = [NSMutableArray new];
for(NSString *key in sortedKeys)
    [sortedValues addObject:[dictFilterValues objectForKey:key]];
于 2016-01-04T09:00:31.073 回答
1

只需将其写在这里,因为我在任何地方都找不到它:要根据值从 NSDictionary 中获取按字母数字排序的 NSDictionary - 在我的情况下这是必要的 - 您可以执行以下操作:

//sort typeDict alphanumeric to show it in order of values
    NSArray *keys = [typeDict allKeys];

    NSArray *sortedKeys = [keys sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
        NSString *first = [typeDict objectForKey:a];
        NSString *second = [typeDict objectForKey:b];
        return [first compare:second];
    }];
    NSLog(@"sorted Array: %@", sortedKeys);

    NSMutableDictionary *sortedTypeDict = [NSMutableDictionary dictionary];
    int counter = 0;
    for(int i=0; i < [typeDict count]; i++){
        NSString *val = [typeDict objectForKey:[sortedKeys objectAtIndex:counter]];
        NSString *thekey = [sortedKeys objectAtIndex:counter];
        [sortedTypeDict setObject:val forKey:thekey];
        counter++;
    }
    NSLog(@"\n\nsorted dict: %@", sortedTypeDict);

没有大碍!

于 2015-01-27T15:22:50.880 回答
0

如果字典中的任何值为空,则使用此代码

NSArray *keys = [typeDict allKeys];   
NSSortDescriptor *sd = [[NSSortDescriptor alloc] initWithKey:nil ascending:YES];
NSArray *sortedKeys = [keys sortedArrayUsingDescriptors:@[sd]];
NSLog(@"SORT 1 %@",sortedKeys);

NSMutableDictionary *sortedTypeDict = [NSMutableDictionary dictionary];
int counter = 0;
for(int i=0; i < [typeDict count]; i++){
    id val = [typeDict objectForKey:[sortedKeys objectAtIndex:counter]];
    NSString *thekey = [sortedKeys objectAtIndex:counter];
    [sortedTypeDict setObject:val forKey:thekey];
    counter++;
}
NSLog(@"\n\nsorted dict: %@", sortedTypeDict);
于 2019-12-27T10:07:42.630 回答