Objective C - 来自JSON的组元素

时间:2015-07-25 13:46:49

标签: ios objective-c json

好吧,我将尝试解释我想要实现的内容。

我有JSON方案,如:

{
  "objects": [
    {
      "title": "Title #1",
      "date": "1446930000"
    },
    {
      "title": "Title #2",
      "date": "1437782400"
    },
    {
      "title": "Title #3",
      "date": "1437912000"
    },
    {
      "title": "Title #4",
      "date": "1446930000"
    },
    {
      "title": "Title #5",
      "date": "1437912000"
    }
  ]
}

我必须按时间对元素进行分组(例如,按天)。已经尝试索引 objects [] 数组,制作'dates'数组( dates [] )然后再次索引数组,索引 dates [] 并检查对象 array [i] = 日期[q] 。但是这种方法确实很差,并且当有很多物体时没有意义。

我还可以将它们分组?

1 个答案:

答案 0 :(得分:0)

您需要创建mutable dictionary

NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithCapacity:objects.count];
for (NSDictionary *object in objects) {
    if (dictionary[object[@"date"]]) {
        // the date was already found
        [(NSMutableArray *)dictionary[object[@"date"]] addObject:object[@"title"]];
    } else {
        // the date was not found
        dictionary[object[@"date"]] = [NSMutableArray arrayWithObject:object[@"title"]];
    }
}

字典使用hash table来确保查找速度快 - 比循环遍历所有键快得多。