0

Using Swift 4

Problem:

I have a core data object graph for a soccer league with two entities: Team and Games, related with a one to many relationship (each Team can have many Games). Each game has two statistics: "goals for", and "goals against". I would like to calculate wins, losses, ties, and points scored game (which is an average). It would be a simple matter to calculate the values each time they are needed, but in a large data structure that accesses these values frequently, I want to know if there is a method that calculates the values only once each time the data changes.

Thanks

Frederic
  • 499
  • 2
  • 7
  • 14
  • 1
    There isn't any that is provided as-is, you'd have to perform `predicateRequests` and compile the data wherever it needs to be stored. Or, you can create a seperate class, which corresponds to a Team's stats, which is then updated everytime a game object is completed. It would just become a simple read the team's current stats from the stats object, and re-calculate with the new inputed data. read up on nspredicates on fetch requests https://www.allaboutswift.com/dev/2016/5/29/asynchronous-core-data-requests – jlmurph Oct 11 '17 at 20:55
  • reason why this works is because past game data, in your case, is immutable. As in, a game will never be re-played, therefore you don't have to worry about the data being held in your Stats object misrepresenting the past entries. Plus, if all you're using is averages, adding new game stats to a team is mathematically simple. Doing it this way wont add much storage need, and it'll save you the CPU overhead of having to parse over many entries every time game data is updated. – jlmurph Oct 11 '17 at 20:57
  • @murphguy what is a `predicateRequests`? How are calculated properties related to fetch requests and predicates? – Willeke Oct 11 '17 at 21:07
  • Duplicate of [CoreData: How to refresh “calculated” attributes?](https://stackoverflow.com/questions/20820415/coredata-how-to-refresh-calculated-attributes). – Willeke Oct 11 '17 at 21:18

0 Answers0