按ASC顺序对NSMutableDictionary进行排序

时间:2019-06-11 18:38:49

标签: objective-c sorting nsdictionary nsmutabledictionary

在我的Xcode项目(Objective-C)中,我将json结果存储在NSMutableDictionary中,但是结果方向错误。

如何在Objective-C上对NSMutableDictionary是ASC订单进行排序。

这是我的NSMutableDictionary

{
    3 =     (
        11,
        12,
        13,
        14,
        15,
        16,
        17,
        18,
        19,
        20
    );
    2 =     (
        2,
        3,
        4,
        5,
        6,
        7,
        8,
        9,
        10
    );
    1 =     (
        0,
        1
    );
    4 =     (
        21,
        22,
        23,
        24,
        25,
        26
    );
}

我希望UITableView部分的排序顺序为1,2,3,4。

1 个答案:

答案 0 :(得分:0)

@rmaddy是正确的,下面是实现代码,非常简单。

- (NSMutableArray *)sortDictionary:(NSMutableDictionary *)dictionary {
    NSArray *sortedKeys = [[dictionary allKeys] sortedArrayUsingSelector:@selector(compare:)];
    NSMutableArray *sortedArray = [NSMutableArray arrayWithCapacity:sortedKeys.count];
    for (NSString *key in sortedKeys) {
        [sortedArray addObject:[dictionary objectForKey:key]];
    }
    return sortedArray;
}

示例

NSDictionary *dict = @{@"3":@{@"3333":@"3333"},
                       @"2":@{@"2222":@"2222"},
                       @"1":@{@"1111":@"1111"},
                       @"4":@{@"4444":@"444"}};

[self sortDictionary:dict];

结果:

sortedArray :(
        {
        1111 = 1111;
    },
        {
        2222 = 2222;
    },
        {
        3333 = 3333;
    },
        {
        4444 = 444;
    }
)