简体   繁体   English

根据属性将对象数组简化为唯一对象

[英]Reducing an array of objects to unique objects based on attributes

Ok. 好。

I have an array with multiple objects populated by my core data stack . 我有一个包含多个由我的核心数据堆栈填充的对象的数组。 Lets say each object has a name, startdate, enddate and amount attribute associated with them 可以说每个对象都有一个与之关联的名称,开始日期,结束日期和数量属性

What I need to do is reduce this array down to only the unique objects (not just values) based on the name, which is an NSString. 我需要做的就是根据名称(即NSString)将此数组缩减为仅唯一的对象(而不仅仅是值)。

I've tried isEqual methods within for loops, while loops and using sets, and I can't seem to figure it out. 我已经尝试过for循环,while循环和使用集内的isEqual方法,但似乎无法弄清楚。

Any ideas? 有任何想法吗?


UPDATE: I should be more clear. 更新:我应该更清楚。 Basically what I want to do is take an existing array, and delete duplicate objects with the same attribute value and end up with an array of unique objects. 基本上,我想做的是获取一个现有的数组,并删除具有相同属性值的重复对象,最后得到一个唯一对象数组。

  1. do a fetch of all your objects with no predicate - result is an array which may contain multiples with the same name string 没有谓词地获取所有对象-结果是一个数组,其中可能包含具有相同名称字符串的多个
  2. iterate over the array creating a new array of strings (copy the name string of each entity) 遍历数组以创建新的字符串数组(复制每个实体的名称字符串)
  3. convert that array into a set - by definition it contains only unique names 将该数组转换为一组-根据定义,它仅包含唯一的名称
  4. access your core data entities as required by doing a fetch with a predicate "name = %@" for any name in the set (or turn the set back into an array for ease of use). 通过对集合中的任何名称进行谓词“ name =%@”提取来访问您的核心数据实体(或将集合转回数组以方便使用)。

Nevermind. 没关系。 I figured it out using a crazy groups of if statements, might not be the most efficient way of doing it, but it garnerd the results I needed. 我用一组疯狂的if语句弄清楚了这可能不是最有效的方法,但是它获得了我需要的结果。

  1. Fetch the objects into an NSArray . 将对象提取到NSArray
  2. Create a NSMutableDictionary . 创建一个NSMutableDictionary
  3. Iterate over the array. 遍历数组。
  4. Check to see if the attribute, used as the key in the dictionary, is already in place, if so continue . 检查用作字典中键的属性是否已经存在,如果continue ,请continue
  5. If not, add it to the dictionary 如果没有,请将其添加到字典中
  6. Once the loop is complete call -allValues on the dictionary. 循环完成-allValues ,在字典上调用-allValues

You now have an array of objects that are unique on that attribute. 现在,您在该属性上具有唯一的对象数组。

If you are going to answer your own question, at least post code to help others with the same problem. 如果您要回答自己的问题,请至少张贴代码以帮助其他遇到相同问题的人。 it may be a solution that works for them as well. 它可能也是一种对他们也有效的解决方案。 If you are asking others to post code and or help you, realize it is a 2 way street 如果您要别人张贴代码和/或帮助您,请意识到这是一条两条路

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

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