Group NSDictionary by dates [duplicate]

非 Y 不嫁゛ 提交于 2019-12-14 01:46:09

问题


I have a NSDictionary and i want to group it creating an array of objects by date

Example of the main NSDictionary:

({

        date = "2014-04-27";
        group = "yellow.png";
        length = 180;

    },
        {

        date = "2014-04-28";
        group = "blue.png";
        length = 180;

    },
        {

        date = "2014-04-27";
        group = "blue.png";
        length = 120;

    })

I want to group something similar as:

2014-04-27 = (
{ 

            date = "2014-04-27";
            group = "yellow.png";
            length = 180;

        },
            {

            date = "2014-04-27";
            group = "blue.png";
            length = 180;

        })


  2014-04-28 = ( {

            date = "2014-04-28";
            group = "blue.png";
            length = 120;

        })

Could someone help me? i have tried many FOR but i cant get it


回答1:


It appears as though your original data structure is an array of dictionaries. Was your question phrased incorrectly? I see each individual dictionary but they are not keyed on anything in the top level data structure.

Assuming that is the case (you have an array called originalArray

NSMutableDictionary *dictionaryByDate = [NSMutableDictionary new];

for(NSDictionary *dictionary in originalArray)
{
    NSString *dateString = dictionary[@"date"];
    NSMutableArray *arrayWithSameDate = dictionaryByDate[dateString];
    if(! arrayWithSameDate)
    {
        arrayWithSameDate = [NSMutableArray new];
        dictionaryByDate[dateString] = arrayWithSameDate;
    }
    [arrayWithSameDate addObject: dictionary];
}

By the end of this, dictionaryByDate will be a dictionary (keyed on date) of arrays (all objects in a given array will be dictionaries with the same date).



来源:https://stackoverflow.com/questions/22288481/group-nsdictionary-by-dates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!