0

I have a CoreData entity named Ticket which represents the work done on a job. Every job has hours and I would like to get all of the hours done for companyX. So for example:

If I have

Verizon: 8
Netflix: 8
AMEX: 8
Verizon: 8

How would I map over all the Verizon jobs and get 16 hours

enter image description here

I can't think of how I would do this although I think I would have to edit the Ticket + CoreDataProperties file.

Would I perform the mapping here

@FetchRequest(entity: Ticket.entity(), sortDescriptors: [])

or somewhere else?

Sergio Bost
  • 2,591
  • 2
  • 11
  • 29
  • 1
    Try computed/derived attributes [PassingCuriosity](https://passingcuriosity.com/2008/computed-attributes-in-core-data-how/) [Avanderlee](https://www.avanderlee.com/core-data/derived-attributes-optimise-fetch-performance/) – lorem ipsum Mar 20 '21 at 22:51
  • 1
    Here is [WWDC video](https://developer.apple.com/videos/play/wwdc2019/230/) it is at about minute 19 – lorem ipsum Mar 20 '21 at 23:05
  • @loremipsum Thanks a lot! I can tell this is sort of arcane knowledge. – Sergio Bost Mar 20 '21 at 23:07
  • Just a bit obscure but very helpful. Here is a [question](https://stackoverflow.com/questions/62770742/core-data-derivation-expression-key-path-uses-an-operator-as-an-intermediate-com) that might help with an `@sum` – lorem ipsum Mar 20 '21 at 23:11

1 Answers1

1

It is pretty obscure but a Computed/Derived attribute does this for you.

A description of an attribute of a Core Data entity that derives its value from one or more other properties.

It is hard to describe but here are some resources

PassingCuriosity

Avanderlee

Here is WWDC video it is at about minute 19

And an SO question that deals with an error with @sum

NSDerivedAttribute

Function names

Data Model Inspector

lorem ipsum
  • 21,175
  • 5
  • 24
  • 48
  • Although I’m using manually created CoreData class but the avanderlee post you shared gives a solution for that too, and still watching WWDC – Sergio Bost Mar 20 '21 at 23:25