Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GROUP BY equivalent for Core Data

I know that I can use @distinctUnionOfObjects to find something like the following in SQL:

SELECT a_value
FROM my_table
GROUP BY a_value;

What I'm looking for is all of the data returned in an array, not just the array of values that matches the group by expression. Essentially, I'm looking for the equivalent of the following SQL query for core data:

SELECT *
FROM my_table
GROUP BY a_value;
like image 595
smtlaissezfaire Avatar asked Feb 01 '11 17:02

smtlaissezfaire


2 Answers

It's analog

SELECT 'Status', COUNT(*) FROM 'Records' GROUP BY 'Status':

NSFetchRequest* fetch = [NSFetchRequest fetchRequestWithEntityName:@"Record"];
NSEntityDescription* entity = [NSEntityDescription entityForName:@"Record"
                                          inManagedObjectContext:myManagedObjectContext];
NSAttributeDescription* statusDesc = [entity.attributesByName objectForKey:@"status"];
NSExpression *keyPathExpression = [NSExpression expressionForKeyPath: @"url"]; // Does not really matter
NSExpression *countExpression = [NSExpression expressionForFunction: @"count:"
                                                          arguments: [NSArray arrayWithObject:keyPathExpression]];
NSExpressionDescription *expressionDescription = [[NSExpressionDescription alloc] init];
[expressionDescription setName: @"count"];
[expressionDescription setExpression: countExpression];
[expressionDescription setExpressionResultType: NSInteger32AttributeType];
[fetch setPropertiesToFetch:[NSArray arrayWithObjects:statusDesc, expressionDescription, nil]];
[fetch setPropertiesToGroupBy:[NSArray arrayWithObject:statusDesc]];
[fetch setResultType:NSDictionaryResultType];
NSError* error = nil;
NSArray *results = [myManagedObjectContext executeFetchRequest:fetch
                                                         error:&error];

Found here

like image 116
Bimawa Avatar answered Oct 05 '22 22:10

Bimawa


You could try using an NSFetchedResultsController object to provide grouping by way of the sectionNameKeyPath construct in the initializer. Note that FRCs are mainly to be used to couple with a table view, but it's not really necessary. This way you could group your results by your sectionNameKeyPath which could be a transient attribute in your model, too.

As a comment, I wouldn't recommend thinking of Core Data in terms of a database, which it isn't. Core Data is built to make it easier for you to persist and manage object relationships. Just because on the iOS it runs on top of SQLite doesn't make it a database replacement.

Reference: NSFRC Reference

like image 39
Saurabh G Avatar answered Oct 05 '22 22:10

Saurabh G