开发者

Reducing an array of objects to unique objects based on attributes

开发者 https://www.devze.com 2023-01-14 11:29 出处:网络
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

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 开发者_StackOverflow中文版to do is reduce this array down to only the unique objects (not just values) based on the name, which is an NSString.

I've tried isEqual methods within for loops, while loops and using sets, and I can't seem to figure it out.

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).


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.


  1. Fetch the objects into an NSArray.
  2. Create a 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.
  5. If not, add it to the dictionary
  6. Once the loop is complete call -allValues on the dictionary.

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

0

精彩评论

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