NSFetchRequest 总和、分组依据和排序

Zyp*_*rax 5 sorting group-by core-data objective-c nsfetchrequest

在我的应用程序中,我试图列出四种最受欢迎​​的产品。
产品受欢迎程度由订单总量决定。

下面的查询是为了说明我想要做什么:

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

下面的代码是我在针对核心数据模型的获取请求中获取它的方法:

// 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;
Run Code Online (Sandbox Code Playgroud)

我的问题是 sortDescriptor,它似乎只允许 Order 的直接属性(应用程序例外)。
排序非常重要,因为它决定将返回哪四个记录。

注意:我正在使用 MagicalRecord 和 Mogenerator。我已经删除了类前缀。

Dmi*_*nko 3

不幸的是,NSSortDescriptor想要一个实际的属性来排序,而不是动态计算的字段。根据您的情况,您可能希望将所需的计数器保存在模型本身上并按其排序,或者获取整个图表并在内存中对其进行排序。