我有一个实体 PackageHistories。我想按 myStore 筛选并按 myShoppingItem 分组,并获取每个组的计数。
我的获取请求编码如下:
let historyRequest = NSFetchRequest(entityName: "PackageHistories")
let storePredicate = NSComparisonPredicate(leftExpression: NSExpression(forKeyPath: "myStore"), rightExpression: NSExpression(forConstantValue: dataStack.currentReceipt.myStore), modifier: NSComparisonPredicateModifier.DirectPredicateModifier, type: NSPredicateOperatorType.EqualToPredicateOperatorType, options: NSComparisonPredicateOptions.NormalizedPredicateOption)
historyRequest.predicate = storePredicate
historyRequest.resultType = NSFetchRequestResultType.DictionaryResultType
let itemDescription = NSExpressionDescription()
itemDescription.name = "ShoppingItems"
itemDescription.expression = NSExpression(forKeyPath: "myShoppingItem")
itemDescription.expressionResultType = .ObjectIDAttributeType
let countDescription = NSExpressionDescription()
countDescription.name = "Popularity"
countDescription.expression = NSExpression(format: "@count.myShoppingItem")
countDescription.expressionResultType = .Integer32AttributeType
historyRequest.propertiesToGroupBy = ["myShoppingItem"]
historyRequest.propertiesToFetch = [itemDescription, countDescription]
historyRequest.sortDescriptors = [NSSortDescriptor(key: "Popularity", ascending: false)]
我的问题是我收到 fatal error :由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“无法为表达式生成选择目标 token :@count.myShoppingItem”
。
最近几个版本是否发生了一些变化,以至于 countDescription.expression = NSExpression(format: "@count.myShoppingItem")
不再是正确的格式?我正在使用 Xcode 7.2 和 iOS 9。
更新:
countDescription.expression = NSExpression(forFunction: "count:", arguments: [itemDescription.expression!])
countDescription.expressionResultType = .Integer32AttributeType
不会崩溃,但它确实给了我官样文章。它不返回整数,它返回某种 NSManagedObjectID。
最佳答案
您的代码看起来没问题。但它不应该是 myShoppingItem.@count
吗?
关于ios - 尝试按一个属性分组并获取核心数据中每组中的实体数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33844950/