Swift 3 Core Data - NSExpression forFunction: “sum:” throws error (“could not cast dictionary to Day”)

感情迁移 提交于 2019-12-21 02:44:07

问题


I have days and tasks. A day has many tasks. Every task has an attribute called "points" and I want to sum all points of the tasks of the current day. I used the code below (found in the book Core Data by tutorials, swift 2 version) and tried to modify it for swift 3 (I also added a predicate, but that's not important). But when I run this code, I get this error:

Could not cast value of type 'NSKnownKeysDictionary1' (0x10d02d328) to 'MyProject.Day'

What am I doing wrong?

    // sum current day's task points 
    let sumRequest: NSFetchRequest<Day> = Day.fetchRequest()
    sumRequest.resultType = .dictionaryResultType

    sumRequest.predicate = NSPredicate(format: "SELF == %@", argumentArray: [Project.Days.current])

    let expressionDescription = NSExpressionDescription()
    expressionDescription.name = "sumOfPoints"
    expressionDescription.expression = NSExpression(forFunction: "sum:", arguments: [NSExpression(forKeyPath: "tasks.points")])
    expressionDescription.expressionResultType = .integer16AttributeType

    sumRequest.propertiesToFetch = [expressionDescription]

    do {
        let results = try managedObject.fetch(sumRequest) as! [NSDictionary] // Here's the line that causes the error
        print("DEN:", results)
    } catch let error as NSError {
        print("DEN:", error.localizedDescription)
    }

I think it has something to do with this line:

let sumRequest: NSFetchRequest<Day> = Day.fetchRequest()

Here, I explicitly say the result will be a Day (I believe that's new in swift 3?). But I don't know how I could change this.

Thank you!


回答1:


This solves my problem:

let sumRequest: NSFetchRequest<NSFetchRequestResult> = Day.fetchRequest()

Instead of putting Dayas NSFetchRequestResult, I put NSFetchRequestResult itself there. Now it's working.

I believe as I set it to a different resultType it's not [Day]anymore that gets returned, so that's why I needed to change that to be more generic or something.



来源:https://stackoverflow.com/questions/39521384/swift-3-core-data-nsexpression-forfunction-sum-throws-error-could-not-ca

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