开发者

iPhone: How to create a NSMutableDictionary which contains multiple sets of data with same key?

开发者 https://www.devze.com 2023-03-07 07:47 出处:网络
{ \"data\": [ { \"data\": [ null, null, 30, 45, 69, 70, 65 ], \"title\": \"title5\" }, { \"data\": [ null, 5, 10, 15, 22,
{

"data": [
    {
        "data": [
            null,
            null,
            30,
            45,
            69,
            70,
            65
        ],
        "title": "title5" 
    },
    {
        "data": [
            null,
            5,
            10,
            15,
            22,
            30 
        ],
        "title": "title4" 
    },
    {
        "data": [
            40,
            55,
        ],
        "title": "title3" 
    },
    {
          "data": [
              null,
            89,
            90,
            85
        ],
        "title": "title2" 
    },
    {
        "data": [
            66,
            77,
            55,
            33,
            50,
            -6,
            -8
        ],
        "title": "title1" 
    } 
],
 "x_labels": [
    6,
    7,
    8,
    9,
    10,
    11,
    12
]
}

I want my dictionary to have same key called "data" and "title" for each set of values it contains as shown by above code.

But when I try to create a 开发者_运维技巧dictionary and try using setValue:forKey: method for the same key or addEntriesFromDictionary: it overwrites each set of data and finally I only get the last set of data which I pushed into my dictionary.

Is there a way, I can do this?


Notice that the first object in the lowest-level dictionary is a list or array. This is the key.

 NSMutableArray * dataArr = [NSMutableArray array];
 NSArray * x_labelArr = [NSArray arrayWithObjects: ...];
 NSMutableDictionary * dict = 
            [NSMutableDictionary dictionaryWithObjectsAndKeys: 
                     arr, @"data", x_labelArr, @"x_labels", nil];

Now you can add individual inner dictionaries to the array, each of which has the same keys:

NSDictionary * innerDict = 
            [NSDictionary dictionaryWithObjectsAndKeys: 
                  someArrayOfData, @"data", someTitle, @"title"];
NSDictionary * innerDict2 = 
            [NSDictionary dictionaryWithObjectsAndKeys: 
                            someOtherArrayOfData, @"data", 
                                 someOtherTitle, @"title"];
[dataArr addObject:innerDict];
[dataArr addObject:innerDict2];


You can add dictionaries to your dictionary; the dictionaries all contain "data"->asdf, "title"->asdf. Or, add an array for a "data" element and add to that. But from what your data looks like, it's more likely you want this.

0

精彩评论

暂无评论...
验证码 换一张
取 消