为CoreData ios 10添加实体内部的属性

时间:2016-12-21 17:19:56

标签: ios core-data swift3

我有一个tableView,并且正在使用来自Coredata的数据填充tableview。数据就像这样分解。

实体 - 人

实体 - 声明 语句实体有一个名为amountOwed的属性,它是十进制类型。

关系是一个人可以有很多陈述,但每个陈述属于一个人。

以下是我想要添加的数据路径。人>声明> AmountOwed。

在tableView函数中,我有一个let表示Person实体。

let person = fetchedResultsController.object(at: indexPath)

我知道它有效,因为我可以打印出这样的人名

print(person.name) // Bob

我希望能够为Statement实体中的每个Person添加所有amountOwed属性,并将它们显示在单元格上。

我一直在尝试关注计算提取的示例,但我似乎并不安静地了解如何定位链接到每个Person实体的语句实体。

 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的keypath就像这样

person[indexPath].statement.amountOwed

2 个答案:

答案 0 :(得分:1)

你可以在一行中完成。如果PersonStatement之间的关系被称为statements,则您可以获得

的总金额
let amountTotal = newPerson.value(forKeyPath: "statements.@sum.amount") as? Int64

将最后的向下广告从Int64更改为适合您的amount属性 - Double或其他任何内容。

答案 1 :(得分:0)

确定public static boolean isValidURL(String urlString) { try { URL url = new URL(urlString); url.toURI(); return true; } catch (Exception exception) { return false; } } 添加:

People+CoreDataClass

并从您的提取中删除所有不必要的代码