【问题标题】:How to Sort NSMutableDictionary in iOS如何在 iOS 中对 NSMutableDictionary 进行排序
【发布时间】:2016-03-01 07:06:32
【问题描述】:

我是 iOS 开发的新手。我正在用 Title、Count、Score 创建 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];

【问题讨论】:

标签: ios nsmutablearray nsmutabledictionary


【解决方案1】:

我尝试了下面的编码。它对我来说很好用

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

【讨论】:

  • 谢谢,它的作品... :)
【解决方案2】:

试试这个代码

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-01
    • 2013-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-03
    相关资源
    最近更新 更多