Sum NSFetchRequest, grouping and sorting

In my application, I am trying to list the four most popular products.
Product popularity is determined by the total value in orders.

Below is an example of what I'm trying to do:

SELECT TOP 4 SUM(quantity) as sumQuantity, Product FROM [Order] GROUP BY Product ORDER BY 1 DESC 

The following is my approach to getting it in a fetch request for my Core Data model:

 // Create an expression to sum the order quantity NSExpressionDescription *sumExpression = [[NSExpressionDescription alloc] init]; sumExpression.name = @"sumQuantity"; sumExpression.expression = [NSExpression expressionWithFormat:@"@sum.%K", OrderAttributes.quantity]; sumExpression.expressionResultType = NSInteger32AttributeType; // Create the fetch request NSFetchRequest *request = [Order createFetchRequest]; request.resultType = NSDictionaryResultType; request.propertiesToFetch = @[OrderRelationships.product, sumExpression]; request.propertiesToGroupBy = @[OrderRelationships.product]; request.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:sumExpression.name ascending:NO]]; request.fetchLimit = 4; 

My problem is sortDescriptor, it only seems to allow direct Order properties (application exception).
The variety is extremely important as it determines which four records will be returned.

Note. I am using MagicalRecord and Mogenerator. I removed the class prefixes.

+4
source share
1 answer

Unfortunately, NSSortDescriptor wants the actual property to be sorted, not a dynamically calculated field. Depending on your situation, you want to either save the required counter on the model itself, or sort by it, or get the entire graph and sort it in memory.

+3
source

All Articles