Mansour
Mansour

Reputation: 535

CoreData Aggregate one to many relationships

I have a CoreData model with the following "architecture": I have a Session entity with system_version as an attribute. Then I have a Views (Session<-->>Views) entity with a delta_time an attribute. Finally I have a "UI_Elements" (Views <-->> UI_Elements) entity with a variable_value attribute. I would like to filter the content according to a specific variable_value value and then display the delta_time average grouped by system_version.

enter image description here

I have tried the following implementation:

            var expressionDescriptions = [AnyObject]()

            expressionDescriptions.append("views_ui.sessions.systemVersion" as AnyObject)
            let expressionDescription = NSExpressionDescription()
            expressionDescription.name = "Average Time"


            expressionDescription.expression = NSExpression(format: "@avg.views_ui.delta_time_number")
            expressionDescription.expressionResultType = .integer32AttributeType
            expressionDescriptions.append(expressionDescription)



            let fetch = NSFetchRequest<NSFetchRequestResult>(entityName: "UI_Elements")
            fetch.predicate = requete
            fetch.propertiesToGroupBy = ["views_ui.sessions.systemVersion"]

            fetch.resultType = .dictionaryResultType
            fetch.sortDescriptors = [NSSortDescriptor(key: "views_ui.sessions.systemVersion", ascending: true, selector: #selector(NSString.localizedStandardCompare(_:)))]
            fetch.propertiesToFetch = expressionDescriptions

            var results:[[String:AnyObject]]?

Unfortunately I got the following error:

CoreData: error: SQLCore dispatchRequest: exception handling request: , Invalid keypath (request for aggregate operation on a toOne-only keypath): views_ui.delta_time_number with userInfo of (null)

Upvotes: 1

Views: 189

Answers (1)

Mansour
Mansour

Reputation: 535

I finally managed to get the desired result by modifying the code as follows:

 let keypathExp = NSExpression(forKeyPath: "views_ui.delta_time_number") 
 expressionDescription.expression = NSExpression(forFunction: "average:", arguments: [keypathExp])

Upvotes: 2

Related Questions