Search code examples
objective-ccore-datansfetchrequestpredicates

Can CoreData return unique entity attributes?


Lets say I have an entity with an attribute called animalType. Within core data I have 10,000 of these entities and there are an unknown amount of different animal types, Eg. dog, cat, bird, etc. Can I tell core data to fetch each animal type and return an array similar to:

@[Dog, Cat, Bird, Fish, ...]

I don't want to fetch an array of entities I just want a unique list of animalTypes. No animalType should be repeated.


Solution

  • Yes, you'll want NSFetchRequest's setReturnsDistinctResults: method, combined with setPropertiesToFetch: and setResultType: NSDictionaryResultType. Basically, the fetch will return an array of dictionaries, and those dictionaries will in turn contain key-value pairs corresponding to the specific properties you fetch-- in your case, each dictionary having one key, animalType, and a distinct value for that key. Converting that into an array like the one you describe would be straightforward.