I have a conceptual question regarding plotting charts in SwiftUI based on data from core data.
Lets say I am building a todo list app and I have a todo entity in core data. This entity has the attributes name and finishDate (the date on which the todo was marked as finished).
To plot these two variables, I need a variable containing each individual day and a variable containing the number of finished tasks on each specific day.
Does anyone know how I would go about creating this data efficiently? I know I can fetch the todo entity data and select the correct attributes. But how do I get the number of finished tasks on each specific day? Ideally without creating those variables using for loops.
It would be really appreciated if anyone can help me.
2
Answers
I’d start with an attribute for the day of the week (which you can derive from the
Date()
value you’re using for completion date). Then you can use either a count fetch request (Cocoa Core Data efficient way to count entities), or a group-by and anNSDictionaryResultType
(extensive code example at https://www.cocoanetics.com/2017/04/group-by-count-and-sum-in-coredata/). The group-by approach will give you a dictionary that looks like this (from the Cocoanetics article):I believe, but don’t know for certain, that you’ll have to compute/store the day-of-week value as an attribute for these grouping approaches to work.
This is easy using CoreData + SwiftUI.
The code below is for iOS15+ but you can do the same thing with an
NSFetchedResultsController
orNSFetchRequest
/@FetchRequest
and then group it. But it will require a bit of effort to stay real time.Also, the code below is meant to work with the standard Apple code for a CoreData project. The only thing I changed in
PersistenceController
is setting a random day for thetimestamp
This is a simple graph