Currently using Core Data. I have one table in which I am trying to retrieve information along these lines:
SELECT item, COUNT(*) FROM myTable GROUP BY item;
in order to produce this type of result:
+---------+------+-------+
| item | COUNT(*) |
+---------+------+-------+
| group 1 | 2 |
| group 2 | 5 |
| group 3 | 8 |
+---------+------+-------+
I had the bright idea to use an NSExpression, with hopes of having Core Data do all the work for me. I am beginning to spin my wheels. The count: expression function is crashing on me. The exception is not very clear. The use of other expression functions, such as sum: doesn't crash the app.
It would be nice to store the results in a NSFetchedResultsController. I've explored other options, none of which aren't too appealing. Would it make more sense to write a SQL query and get it over with, rather than to use Core Data as a SQL wrapper in this case?
For your reference source code is below.
NSExpression *keyPathExpression = [NSExpression expressionForKeyPath:@"item"];
NSExpression *totalExpression = [NSExpression expressionForFunction:@"count:" arguments:[NSArray arrayWithObject:keyPathExpression]];
NSExpressionDescription * totalExpressionDescription = [[NSExpressionDescription alloc] init];
[totalExpressionDescription setExpression:totalExpression];
[totalExpressionDescription setExpressionResultType:NSInteger64AttributeType];
[totalExpressionDescription setName:@"totalInstances"];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"myEntity" inManagedObjectContext:self.managedObjectContext];
NSArray *propertiesToFetch = [[NSArray alloc] initWithObjects:strFieldName, totalExpressionDescription, nil];
[fetchRequest setEntity:entity];
[fetchRequest setReturnsDistinctResults:YES];
[fetchRequest setResultType:NSDictionaryResultType];
[fetchRequest setPropertiesToFetch:propertiesToFetch];
[fetchRequest setFetchBatchSize:20];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:strFieldName ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[fetchRequest setSortDescriptors:sortDescriptors];
NSFetchedResultsController* aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:[self managedObjectContext] sectionNameKeyPath:nil cacheName:nil];
...
NSError *error = nil;
if (![self.fetchedResultsController performFetch:&error])
{
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
Best Answer
This is possible with NSExpression as you originally proposed, in my contrived example I have an entity called "Person" with a property called "emailAddress" that I wish to get the count for.
I wrote a snippet of code to pre-populate the database with 1000 records:
The above code will insert each email address 200 times, here are the results: