Swift 4 CoreData NSFetchRequest: sum over computed variable

那年仲夏 提交于 2021-01-28 08:50:41

问题


I'm using CoreData for persistence and would like to use a NSFetchRequest with an NSExpression(forFunction: "sum:" ...).

I have three Entities

Entity A:
    name: String
    value: Int64
Entity B:
    name: String
Entity C:
    relationship1: A
    relationship2: B
    value: Int64

I have a separate Entity for a relationship between an A- and an B-Entity, because a relationship also has an Int64 Value.

I guess this is the easiest solution not to sum up one attribute of a given set of Cs (using a NSPredicate to filter) but to sum up the product of C.value and C.relationship1.value. I found no solution to pass the terms of the sum (C.value * C.relationship1.value) as NSExpressions because of the multiplication. But I thought it would be easier to use computed variables instead. (Though this feels a little inefficient) But for computed variables "forKey:" is not working, "forVariable:" neither. I may have used it the wrong way anyway. Anyway, when the code is executed the App crashes.

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unsupported argument to sum : (
"$C.product")'


import Foundation
import CoreData

@objc(C)
public class C: NSManagedObject {

@objc var product : Int64 {
    if let test = self.relationship1.value {
        return test * self.value
    } else {
        return 0
    }
  }
}

The NSFetchRequest looks like this:

let fetchRequest = NSFetchRequest<NSDictionary>(entityName: "C")
fetchRequest.resultType = .dictionaryResultType

let sumExpressionDesc = NSExpressionDescription()
sumExpressionDesc.name = "returnValue"

let predicate = NSPredicate(format: "C.relationship1.name == %@", name)

let expression = NSExpression(forkeyPath: #keyPath(C.product)) //This is the line that crashes the App
sumExpressionDesc.expression = NSExpression(forFunction: "sum:", arguments: [expression])
sumExpressionDesc.expressionResultType = .integer32AttributeType

fetchRequest.predicate = predicate
fetchRequest.propertiesToFetch = [sumExpressionDesc]

do {
    let results = try managedObjectContext.fetch(fetchRequest)
    (...)

Accessing the computed value product is no problem elsewhere. It's just not working in combination with the NSFetchRequest.

Thanks in advance

来源:https://stackoverflow.com/questions/49099914/swift-4-coredata-nsfetchrequest-sum-over-computed-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!