如何在 iOS 中对 NSMutableDictionary 进行排序

How to Sort NSMutableDictionary in iOS

我是 iOS 开发的新手。我正在创建带有标题、计数、分数的 NSMutableDictionary。现在我想用 Count 的基数按降序对我的 NSMutableDictionary 进行排序。请帮助我。

    self.top3_Question_Array = [[NSMutableArray alloc] init]; 

    NSMutableDictionary *item = [[NSMutableDictionary alloc] init];
    [item setValue: [NSString stringWithFormat: itemName] forKey:@"Title"];
    [item setValue: [NSNumber numberWithInteger: itemCount] forKey:@"Count"];
    [item setValue: [NSNumber numberWithFloat: itemScore] forKey:@"Score"];


    [self.top3_Question_Array addObject: item1];

试试这个代码

NSArray *myArray = @[@{@"Title" : @"Hello", @"Count":@"3", @"Score":@"100"}, @{@"Title" : @"Hello", @"Count":@"2", @"Score":@"100"}, @{@"Title" : @"Hello", @"Count":@"1", @"Score":@"100"}, @{@"Title" : @"Hello", @"Count":@"4", @"Score":@"100"}];
    NSSortDescriptor *descriptor = [NSSortDescriptor sortDescriptorWithKey:@"Count"
                                                                 ascending:NO
                                                                  selector:@selector(localizedCaseInsensitiveCompare:)];
    NSArray *sorted_array = [myArray sortedArrayUsingDescriptors:@[descriptor]];
    NSLog(@"sorted_array: %@", sorted_array);

我在下面试过 coding.it 对我来说很好

NSMutableDictionary *item = [[NSMutableDictionary alloc] init];
[item setValue:[NSString stringWithFormat: itemName] forKey:@"Title"];
[item setValue: [NSNumber numberWithInteger: itemCount] forKey:@"Count"];
[item setValue: [NSNumber numberWithFloat: itemScore] forKey:@"Score"];

[top3_Question_Array addObject:item];


NSSortDescriptor *countDescriptor = [[NSSortDescriptor alloc] initWithKey:@"Count" ascending:NO];
NSArray *descriptors = [NSArray arrayWithObjects:countDescriptor, nil];
NSArray *sortedArrayOfDictionaries = [top3_Question_Array sortedArrayUsingDescriptors:descriptors];
NSLog(@"sorted array of dictionaries: %@", sortedArrayOfDictionaries);

预期输出也是

  sorted array of dictionaries: (
    {
    Count = 2;
    Score = 30;
    Title = Cholate;
 }
)