Getting NSDictionary keys sorted by their respective values

前端 未结 5 854
广开言路
广开言路 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: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];
    }
    

提交回复
热议问题