Getting NSDictionary keys sorted by their respective values

前端 未结 5 833
广开言路
广开言路 2020-11-27 14:59

I have an NSMutableDictionary with integer values, and I\'d like to get an array of the keys, sorted ascending by their respective values. For example, with thi

相关标签:
5条回答
  • 2020-11-27 15:24

    The NSDictionary Method keysSortedByValueUsingComparator: should do the trick.

    You just need a method returning an NSComparisonResult that compares the object's values.

    Your Dictionary is

    NSMutableDictionary * myDict;
    

    And your Array is

    NSArray *myArray;
    
    myArray = [myDict keysSortedByValueUsingComparator: ^(id obj1, id obj2) {
    
         if ([obj1 integerValue] > [obj2 integerValue]) {
    
              return (NSComparisonResult)NSOrderedDescending;
         }
         if ([obj1 integerValue] < [obj2 integerValue]) {
    
              return (NSComparisonResult)NSOrderedAscending;
         }
    
         return (NSComparisonResult)NSOrderedSame;
    }];
    

    Just use NSNumber objects instead of numeric constants.

    BTW, this is taken from: https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/Collections/Articles/Dictionaries.html

    0 讨论(0)
  • 2020-11-27 15:40

    NSDictionary has this neat method called allKeys.

    If you want the array to be sorted though, keysSortedByValueUsingComparator: should do the trick.

    Richard's solution also works but makes some extra calls you don't necessarily need:

    // Assuming myDictionary was previously populated with NSNumber values.
    NSArray *orderedKeys = [myDictionary keysSortedByValueUsingComparator:^NSComparisonResult(id obj1, id obj2){
        return [obj1 compare:obj2];
    }];
    
    0 讨论(0)
  • 2020-11-27 15:42

    Here's a solution:

    NSDictionary *dictionary; // initialize dictionary
    NSArray *sorted = [[dictionary allKeys] sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        return [[dictionary objectForKey:obj1] compare:[dictionary objectForKey:obj2]];
    }];
    
    0 讨论(0)
  • 2020-11-27 15:45

    The simplest solution:

    [dictionary keysSortedByValueUsingSelector:@selector(compare:)]

    0 讨论(0)
  • 2020-11-27 15:46

    Here i have done something like this:

    NSMutableArray * weekDays = [[NSMutableArray alloc] initWithObjects:@"Sunday",@"Monday",@"Tuesday",@"Wednesday",@"Thursday",@"Friday",@"Saturday", nil];
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
    NSMutableArray *dictArray = [[NSMutableArray alloc] init];
    
    for(int i = 0; i < [weekDays count]; i++)
    {
        dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:i],@"WeekDay",[weekDays objectAtIndex:i],@"Name",nil];
        [dictArray addObject:dict];
    }
    NSLog(@"Before Sorting : %@",dictArray);
    
    @try
    {
        //for using NSSortDescriptor
        NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"WeekDay" ascending:YES];
        NSArray *descriptor = @[sortDescriptor];
        NSArray *sortedArray = [dictArray sortedArrayUsingDescriptors:descriptor];
        NSLog(@"After Sorting : %@",sortedArray);
    
        //for using predicate
        //here i want to sort the value against weekday but only for WeekDay<=5
       int count=5;
        NSPredicate *Predicate = [NSPredicate predicateWithFormat:@"WeekDay <=%d",count];
        NSArray *results = [dictArray filteredArrayUsingPredicate:Predicate];
    
        NSLog(@"After Sorting using predicate : %@",results);
    }
    @catch (NSException *exception)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Sorting cant be done because of some error" message:[NSString stringWithFormat:@"%@",exception] delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil];
        [alert setTag:500];
        [alert show];
        [alert release];
    }
    
    0 讨论(0)
提交回复
热议问题