CoreData get distinct values of Attribute

前端 未结 4 2256
轻奢々
轻奢々 2020-12-02 08:06

I\'m trying to setup my NSFetchRequest to core data to retrieve the unique values for a specific attribute in an entity. i.e.

an entity with the follow

4条回答
  •  遥遥无期
    2020-12-02 08:23

    You're trying to use Core Data like a procedural data base instead of as an object graph manager as the API intended, so you won't find an easy way to do this.

    There isn't a straight forward way to do this in Core Data because Core Data is concerned with objects instead of values. Since managed objects are guaranteed to be unique, Core Data doesn't much care about each object's values or whether they are duplicates or some other object's values.

    To find the unique values:

    1. Perform a fetch by specific value. That will give you an array of dictionaries with a key name and a value of the name string itself.
    2. On the returned array in (1) use a set collection operator to return a set of unique values.

    So, something like:

    NSSet *uniqueNames=[fetchedNameDicts valueForKeyPath:@"@distinctUnionOfSets.name"];
    

    ... which will return a set of NSString objects all with a unique value.

提交回复
热议问题