首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >NSFetchRequest和、分组与排序

NSFetchRequest和、分组与排序
EN

Stack Overflow用户
提问于 2013-02-10 04:35:59
回答 1查看 2K关注 0票数 5

在我的应用程序中,我试图列出四种最受欢迎的产品。

产品的受欢迎程度取决于订单的总数量。

下面的查询是为了说明我想要做的事情:

代码语言:javascript
运行
复制
SELECT     TOP 4  SUM(quantity) as sumQuantity, Product
FROM       [Order]
GROUP BY   Product
ORDER BY   1 DESC

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

代码语言:javascript
运行
复制
// 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。我已经删除了类前缀。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-02-10 04:54:45

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

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14794761

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档