Objective-C:基于字典条目对NSDictionary排序的键

问题描述 投票:13回答:5

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

objective-c xcode cocoa-touch
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];
}];

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将包含按其对应对象排序的键。


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]];

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);

没什么大不了!


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);
© www.soinside.com 2019 - 2024. All rights reserved.