Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you specify "select unique name from ..." with NSPredicate?

I've got some data stored in Core Data that looks something like:

| name | identifier | other_stuff |

I need to display the names in a UITableView, but I only want to display the names with unique name-identifier pairs. So for:

John | 3 | foo
Betty | 4 | foo
Betty | 4 | bar

I only want the query to return John, Betty. Something like "select unique name, identifier from table."

Any way to do this with NSPredicate, or do I need to pour the de-duped fields into a different container, then search on that?

like image 755
James Moore Avatar asked Dec 11 '09 05:12

James Moore


2 Answers

Core Data is an object graph management framework that just happens to (optionally) persist that object graph to a SQL persistent store. There is no way to query object attributes, just objects. You can query the instances then, from the resulting array:

NSArray *instances; //from -[NSManagedObject executeFetchRequest:error:]
NSArray *uniqueNames = [instances valueForKeyPath:@"@distinctUnionOfObjects.name"];

assuming the name is in the name property.

If what you want is for each user to have one name, one id and multiple {foo,bar,...}, then you should model the situation as a user entity with name and id and a to-many relationship to an entity that represents foo/bar/etc.

You can find more information about the @distinctUnionOfObjects (and other collection operators) in the Collection Operators section of the Key Value Coding Guide.

like image 145
Barry Wark Avatar answered Oct 26 '22 23:10

Barry Wark


Since this is Core Data, check out -[NSFetchRequest setReturnsDistinctObjects:].

like image 34
Dave DeLong Avatar answered Oct 27 '22 00:10

Dave DeLong