以有序的方式从 NSDictionary 获取键

Getting keys from NSDictionary in ordered manner

我有 JSON 这样的响应:

 {
    "graphdata": {
        "2018-02-27 to 2018-03-05": {
            "historical": 2.93,
            "datewise": 2.82,
            "ordno": 3595,
            "revno": 89
        },
        "2018-03-06 to 2018-03-12": {
            "historical": 2.92,
            "datewise": 2.62,
            "ordno": 3780,
            "revno": 87
        },
        "2018-03-13 to 2018-03-19": {
            "historical": 2.92,
            "datewise": 3.16,
            "ordno": 3742,
            "revno": 86
        },
        "2018-03-20 to 2018-03-26": {
            "historical": 2.93,
            "datewise": 3.17,
            "ordno": 3745,
            "revno": 70
        },
        "2018-03-27 to 2018-04-02": {
            "historical": 2.93,
            "datewise": 3.08,
            "ordno": 4242,
            "revno": 84
        },
        "2018-04-03 to 2018-04-09": {
            "historical": 2.93,
            "datewise": 3.29,
            "ordno": 3575,
            "revno": 79
        },
        "2018-04-10 to 2018-04-16": {
            "historical": 2.94,
            "datewise": 3.19,
            "ordno": 3629,
            "revno": 69
        },
        "2018-04-17 to 2018-04-23": {
            "historical": 2.94,
            "datewise": 3.33,
            "ordno": 4211,
            "revno": 42
        },
        "2018-04-24 to 2018-04-30": {
            "historical": 2.94,
            "datewise": 0,
            "ordno": 1638,
            "revno": 0
        }
    }
}

现在,当我使用 allKeys 方法时,我会以这样无序的方式获取密钥:

(
    "2018-03-13 to 2018-03-19",
    "2018-04-03 to 2018-04-09",
    "2018-03-20 to 2018-03-26",
    "2018-04-10 to 2018-04-16",
    "2018-04-17 to 2018-04-23",
    "2018-04-24 to 2018-04-30",
    "2018-03-27 to 2018-04-02",
    "2018-02-27 to 2018-03-05",
    "2018-03-06 to 2018-03-12"
)

如何以有序的方式获取这些信息,比如开始时间应该是:“2018-02-27 到 2018-03-05”,

NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"yyyy-MM-dd"];
NSArray *sortedArray = [yourArray sortedArrayUsingComparator:^NSComparisonResult(NSString *obj1, NSString *obj2) {
    NSDate *d1 = [df dateFromString: obj1];
    NSDate *d2 = [df dateFromString: obj2];
    return [d1 compare: d2];
}];

注意:根据你的日期设置日期格式

(((jsonDict.object(forKey: "graphdata") as! NSDictionary).allKeys) as! [String]).sorted(by: <) as NSArray

这里的 jsonDict 是你的父级 NSDictionary

每个字典都是键值对的无序集合。

Use a DictionaryLiteral instance when you need an ordered collection of key-value pairs and don’t require the fast key lookup that the Dictionary type provides.

我使用 sortedArrayUsingComparator 解决了这个问题:

   NSArray *sortedKeys = [[myDictionary allKeys] sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
        return [a compare:b];
    }];