Objective c NSFETCH请求和、分组依据和排序
在我的应用程序中,我试图列出四种最受欢迎的产品。Objective c NSFETCH请求和、分组依据和排序,objective-c,sorting,core-data,group-by,nsfetchrequest,Objective C,Sorting,Core Data,Group By,Nsfetchrequest,在我的应用程序中,我试图列出四种最受欢迎的产品。 产品受欢迎程度取决于订单的总数量 下面的查询是为了说明我正在尝试做什么: SELECT TOP 4 SUM(quantity) as sumQuantity, Product FROM [Order] GROUP BY Product ORDER BY 1 DESC 下面的代码是我根据核心数据模型在获取请求中获取它的方法: // Create an expression to sum the order quant
产品受欢迎程度取决于订单的总数量 下面的查询是为了说明我正在尝试做什么:
SELECT TOP 4 SUM(quantity) as sumQuantity, Product
FROM [Order]
GROUP BY Product
ORDER BY 1 DESC
下面的代码是我根据核心数据模型在获取请求中获取它的方法:
// 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;
我的问题是sortDescriptor,它似乎只允许订单的直接属性(应用程序例外)。排序非常重要,因为它决定将返回哪四条记录
注意:我正在使用MagicalRecord和Mogenerator。我已经删除了类前缀。不幸的是,
NSSortDescriptor
需要一个实际属性进行排序,而不是动态计算字段。根据您的情况,您可能希望在模型本身上保存所需计数器并按其排序,或者获取整个图形并在内存中排序。跟踪产品中的计数器对我来说不是一个真正的选择。我与服务器同步,这样很快就会出现问题和不一致。这是一个很大的限制。谢谢你的帮助。