如何获得CoreData表达查询的结果没有错误
问题描述:
概述:
我想学习如何获取从核心数据存储的某些统计特性(例如总和,平均,最小值,最大值)。我用下面的代码成功地检索了一个字典的平均值,但是我必须以字典的形式得到结果。如何获得CoreData表达查询的结果没有错误
目标:
理想情况下,我想通过扩展,是由Xcode的核心数据自动生成自定义管理对象类“联系”管理对象模型得到的结果与查询的全部结果一起。到目前为止,我一直没有成功。无论我尝试什么,我都会得到类似的错误。
错误:
NSManagedObjectResultType not compatible with contents of propertiesToFetch'or similar
代码:
func avgdemoFloat()->Float{
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let result:Float = 0
do{
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Contact")
let keypathExp = NSExpression(forKeyPath: "demoFloat")
let expression = NSExpression(forFunction: "average:", arguments: [keypathExp])
let avg = NSExpressionDescription()
avg.expression = expression
avg.name = "avg"
avg.expressionResultType = .floatAttributeType
request.returnsObjectsAsFaults = false
request.propertiesToFetch = [avg]
let results = try context.fetch(request)
print(results)
}
我没有足够的经验来排序了这一点。谢谢你的帮助。
答
当您指定propertiesToFetch
的resultType
需要设置如下图所示:
request.resultType = . dictionaryResultType
对不起,我不太明白的问题,你想找到一个特定领域的平均水平? – user1046037
是的,我想获得Flover的'demofloat'的平均值,但这仅仅是一个例子。 – Frederic