我已经在谷歌和SE上找到了我无法找到问题的答案,所以如果我忽略了可能是一个简单的解决方案,我表示歉意。我还是绿色的,所以我可能没有使用正确的搜索字词。 :)
好吧,我觉得我99%到了我想成为的地方。我有以下类函数:
class func fetchGroupTotal(_ group: Int, for managedObjectContext: NSManagedObjectContext) -> Double {
let fetchRequest: NSFetchRequest<Group> = Group.fetchRequest()
let keyPathExpression = NSExpression(forKeyPath: "accounts.balance")
let sumExpression = NSExpression(forFunction: "sum:", arguments: [keyPathExpression])
let expressionDescription = NSExpressionDescription()
expressionDescription.name = "groupSum"
expressionDescription.expression = sumExpression
expressionDescription.expressionResultType = .decimalAttributeType
fetchRequest.propertiesToFetch = [expressionDescription]
fetchRequest.resultType = .dictionaryResultType
do {
let results = try managedObjectContext.execute(fetchRequest)
print("\(results)")
return results.value(forKey: "groupSum") as! Double
} catch {
fatalError("Error fetching SUM: \(error)")
}
}
简而言之,我试图在sum
关系上做accounts
,而这部分似乎正在发挥作用。当我尝试访问我定义的groupSum
属性时,会出现问题。我收到以下错误:
Terminating app due to uncaught exception 'NSUnknownKeyException', reason:
'[<NSAsynchronousFetchResult 0x600000288de0> valueForUndefinedKey:]: this class is not
key value coding-compliant for the key groupSum.'
如何从结果中获取groupSum
?
答案 0 :(得分:0)
呼!那是一个艰难的时刻,但在谷歌搜索失败后,我终于找到了found my answer。一旦我对我fetchRequest
的声明进行了更改,我就能够以groupSum
的身份访问我的[NSDictionary]
媒体资源。
对于那些可能感兴趣的人,这是我的函数的最终版本:
class func fetchTotal(_ group: Int, for managedObjectContext: NSManagedObjectContext) -> Double {
// Right here is where the magic happens:
let fetchRequest: NSFetchRequest<NSFetchRequestResult> = Group.fetchRequest()
let keyPathExpression = NSExpression(forKeyPath: "accounts.balance")
let sumExpression = NSExpression(forFunction: "sum:", arguments: [keyPathExpression])
let expressionDescription = NSExpressionDescription()
expressionDescription.name = "groupSum"
expressionDescription.expression = sumExpression
expressionDescription.expressionResultType = .decimalAttributeType
fetchRequest.propertiesToFetch = [expressionDescription]
fetchRequest.resultType = .dictionaryResultType
fetchRequest.returnsDistinctResults = true
do {
let results = try managedObjectContext.fetch(fetchRequest).first
if let result = results as? NSDictionary {
return result.value(forKey: "groupSum") as! Double
}
return 0.00
} catch {
fatalError("Error fetching SUM: \(error)")
}
}