【发布时间】:2016-09-15 22:41:14
【问题描述】:
我有日子和任务。一天有很多任务。每个任务都有一个名为“积分”的属性,我想总结当天任务的所有积分。我使用了下面的代码(在 Core Data by tutorials, swift 2 版本中找到)并尝试为 swift 3 修改它(我还添加了一个谓词,但这并不重要)。但是当我运行这段代码时,我得到了这个错误:
无法将“NSKnownKeysDictionary1”(0x10d02d328) 类型的值转换为“MyProject.Day”
我做错了什么?
// 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)
}
我认为这与这条线有关:
let sumRequest: NSFetchRequest<Day> = Day.fetchRequest()
在这里,我明确地说结果将是一天(我相信这是 swift 3 中的新功能?)。但我不知道如何才能改变这一点。
谢谢!
【问题讨论】: