gpt4 book ai didi

Swift 3 核心数据 - NSExpression forFunction : "sum:" throws error ("could not cast dictionary to Day")

转载 作者:搜寻专家 更新时间:2023-10-31 08:17:58 24 4
gpt4 key购买 nike

我有日子和任务。一天有很多任务。每个任务都有一个名为“点数”的属性,我想总结当天任务的所有点数。我使用了下面的代码(在教程的核心数据一书中找到,swift 2 版本)并尝试为 swift 3 修改它(我还添加了一个谓词,但这并不重要)。但是当我运行这段代码时,我得到了这个错误:

Could not cast value of type 'NSKnownKeysDictionary1' (0x10d02d328) to '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 中的新功能?)。但我不知道如何改变它。

谢谢!

最佳答案

这解决了我的问题:

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

我没有将Day作为NSFetchRequestResult,而是将NSFetchRequestResult 本身放在那里。现在可以使用了。

我相信当我将它设置为不同的 resultType 时,它不再返回 [Day],所以这就是为什么我需要将其更改为更通用或某物。

关于Swift 3 核心数据 - NSExpression forFunction : "sum:" throws error ("could not cast dictionary to Day"),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39521384/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com