简体   繁体   English

Objective-C合并两个字典数组

[英]objective-c merge two arrays of dictionaries

I have what I think is an interesting question. 我有一个有趣的问题。 I have two arrays which I need to merge and sort. 我有两个需要合并和排序的数组。 Each array is an array of dictionary objects, but the structure of each dictionary object is different. 每个数组都是字典对象的数组,但是每个字典对象的结构都不同。 So one array contains elements that each contain a list of, say, 12 keys/values. 因此,一个数组包含的元素每个都包含例如12个键/值的列表。 The other array has elements that contain a list of, say 15 keys/values. 另一个数组具有包含例如15个键/值的列表的元素。 Some of the keys/values might be the same, but not necessarily in the same order, and not necessarily formatted the same (eg, the date field is formatted differently in each array). 一些键/值可能是相同的,但不一定是相同的顺序,也不一定是相同的格式(例如,日期字段在每个数组中的格式都不同)。

What I need to do (eventually) is combine them, and sort on one common key - the date field. 我需要做的(最终)是将它们组合在一起,并按一个公用键(日期字段)排序。

I don't think an array can have elements with different structures across individual elements, can it? 我不认为数组可以具有跨单个元素具有不同结构的元素,不是吗? I've never used a language that will do this, although I ask because I wouldn't be surprised if objective-c could. 尽管我问过一遍,但我从未使用过能够做到这一点的语言,因为如果Objective-C可以实现,我不会感到惊讶。

Anyway, I have been reading Apple's documentation, and there are a lot of great sorting and merging algorithms already provided. 无论如何,我一直在阅读Apple的文档,并且已经提供了很多很棒的排序和合并算法。 But I could use some help deciding on what approach to use. 但是我可以使用一些帮助来决定使用哪种方法。

The fact is, I only need about 5 fields, so I feel like I want to create a third array of dictionaries with the structure I want, and then transfer all items into it, then sort after. 事实是,我只需要5个字段,所以我觉得我想用所需的结构创建第三个字典数组,然后将所有项目转移到其中,然后进行排序。 But where do I start? 但是我从哪里开始呢?

If anyone has any experience with this I'd appreciate some guidance. 如果有人对此有任何经验,我将不胜感激。

In Objective-C you can have an NSArray with any type of object in it.Structure,that consists only of NSArrays , NSSets and NSDictionaries is called Collection . Objective-C中,您可以拥有一个包含任何对象类型的NSArray 。仅由NSArraysNSSetsNSDictionaries组成的结构称为Collection

So you can merge them into one and easily sort it by date 因此,您可以将它们合并为一个,并轻松按日期对其进行排序

So, after merge,you could sort your array like this 因此,合并后,您可以像这样对数组进行排序

NSSortDescriptor *sortByDateDescriptor = [[NSSortDescriptor alloc] initWithKey:@"date"
                                              ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortByDateDescriptor];
NSArray *sortedArray = [mergedArray sortedArrayUsingDescriptors:sortDescriptors];   

To merge to NSMutableArray's ,just use [firstrray addObjectsFromArray: secondArray]; 要合并到NSMutableArray ,只需使用[firstrray addObjectsFromArray: secondArray];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM