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!
This solves my problem:
let sumRequest: NSFetchRequest<NSFetchRequestResult> = Day.fetchRequest()
Instead of putting Day
as 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With