Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting NSDictionary keys sorted by their respective values

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


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

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

The simplest solution:

[dictionary keysSortedByValueUsingSelector:@selector(compare:)]


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