【发布时间】:2023-03-28 11:45:01
【问题描述】:
我有一个 tableView,该 tableview 正在填充来自 Coredata 的数据。数据是这样分解的。
实体 - 人
实体 - 声明 语句实体有一个名为amountOwed的属性,它是十进制类型。
关系是一个人可以有许多陈述,但每个陈述属于一个人。
这是我要添加的数据的路径。人员 > 报表 > AmountOwed。
在 tableView 函数中,我有一个代表 Person 实体的 let。
let person = fetchedResultsController.object(at: indexPath)
我知道它的工作原理,因为我可以像这样打印出人名
print(person.name) // Bob
我想要做的是将 Statement 实体中每个 Person 的所有 amountOwed 属性相加,并将它们显示在一个单元格上。
我一直在尝试按照计算获取的示例进行操作,但我似乎不太了解如何定位与每个 Person 实体相关联的 Statements 实体。
let fetchRequest = NSFetchRequest<NSDictionary>(entityName:"statement")
fetchRequest.resultType = .dictionaryResultType
let sumExpressionDesc = NSExpressionDescription()
sumExpressionDesc.name = "sumDeals"
let specialCountExp = NSExpression(forKeyPath: #keyPath(Person.statement[indexPath].amountOwed))
sumExpressionDesc.expression = NSExpression(forFunction: "sum:", arguments: [specialCountExp])
sumExpressionDesc.expressionResultsType = .interger32AttributeType
fetchRequest.propertiesToFetch = [sumExpressionDesc]
do{
let results = try coreDataStack.managedContext.fetch(fetchRequest)
let resultDict = results.first!
let numDeals = resultDict["sumDeals"]
print(numDeals!)
}
catch let error as NSError{
print("Count not fetched \(error), \(error.userInfo)")
}
我需要获取 Statement 实体还是应该只使用 FetchedREsultsController?如果我确实使用了我的 fetchedResultsController,Statement Entity 的键路径是否看起来像这样
person[indexPath].statement.amountOwed
【问题讨论】: