天天看點

iOS開發常見Bug_不要被NSLog迷惑(NSDictionary的無序性)

今天被一個bug困擾了很久,最後發現根本原因是由于NSDictionary的無序性引起,為了加深印象,詳細總結如下:

NSDictionary *testDict = [TestUtil getLocalDataFromJsonFile];
    NSLog (@"testDict: %@", testDict);
    for (NSString *key in testDict) {
        NSLog (@"key: %@", key);
    }
           

其中jsonFile中json如下:

{
    "1": "1",
    "2": "2",
    "3": "3",
    "4": "4",
    "5": "5",
    "6": "6",
    "7": "7",
    "8": "8",
    "9": "9",
    "10": "10",
    "11": "11",
    "12": "12",
    "13": "13",
    "14": "14",
    "15": "15",
    "16": "16",
    "17": "17",
    "18": "18",
    "19": "19",
    "20": "20",
    "21": "21",
    "22": "22",
    "23": "23"
}
           

列印結果如下:

2014-08-06 23:01:34.749 PPTVSports[408:90b] testDict: {

    1 = 1;

    10 = 10;

    11 = 11;

    12 = 12;

    13 = 13;

    14 = 14;

    15 = 15;

    16 = 16;

    17 = 17;

    18 = 18;

    19 = 19;

    2 = 2;

    20 = 20;

    21 = 21;

    22 = 22;

    23 = 23;

    3 = 3;

    4 = 4;

    5 = 5;

    6 = 6;

    7 = 7;

    8 = 8;

    9 = 9;

}

2014-08-06 23:01:34.750 PPTVSports[408:90b] key: 18

2014-08-06 23:01:34.751 PPTVSports[408:90b] key: 10

2014-08-06 23:01:34.751 PPTVSports[408:90b] key: 19

2014-08-06 23:01:34.751 PPTVSports[408:90b] key: 11

2014-08-06 23:01:34.752 PPTVSports[408:90b] key: 12

2014-08-06 23:01:34.752 PPTVSports[408:90b] key: 1

2014-08-06 23:01:34.753 PPTVSports[408:90b] key: 20

2014-08-06 23:01:34.753 PPTVSports[408:90b] key: 2

2014-08-06 23:01:34.753 PPTVSports[408:90b] key: 13

2014-08-06 23:01:34.754 PPTVSports[408:90b] key: 3

2014-08-06 23:01:34.754 PPTVSports[408:90b] key: 21

2014-08-06 23:01:34.754 PPTVSports[408:90b] key: 14

2014-08-06 23:01:34.755 PPTVSports[408:90b] key: 4

2014-08-06 23:01:34.755 PPTVSports[408:90b] key: 5

2014-08-06 23:01:34.755 PPTVSports[408:90b] key: 15

2014-08-06 23:01:34.756 PPTVSports[408:90b] key: 22

2014-08-06 23:01:34.756 PPTVSports[408:90b] key: 6

2014-08-06 23:01:34.756 PPTVSports[408:90b] key: 23

2014-08-06 23:01:34.757 PPTVSports[408:90b] key: 7

2014-08-06 23:01:34.757 PPTVSports[408:90b] key: 16

2014-08-06 23:01:34.757 PPTVSports[408:90b] key: 8

2014-08-06 23:01:34.759 PPTVSports[408:90b] key: 17

2014-08-06 23:01:34.759 PPTVSports[408:90b] key: 9

通過上面的代碼,你看到了什麼?

NSDictionary的debugDescription方法得到的輸出列印的順序和原始的Json沒有半毛錢關系,和枚舉NSDictionary的allkeys的順序也沒有半毛錢關系。

NSDictionary具有無序性,是以切記千萬不能依賴NSDictionary的輸出誤以為枚舉NSDictionary的allkeys也會得到同樣的順序。

尼瑪,理論不紮實,debug小半天啊,有木有~

下一篇: idea bug集合