For my SwiftUI view, I am trying to create an ObservableObject that fetches some data from a Core Data entity, and repackages it into a dictionary that I can use for the new Charts UI. The view is created just fine, but I can't figure out how to listen and respond to changes in the data. If I used a @FetchRequest directly, it would listen to the changes and respond automatically, but here I manually fetch items using a NSFetchRequest
class CJChartsDataDataSource: ObservableObject {
@Published var cjCountItemsForDates = [Date: NSNumber]()
init(context: NSManagedObjectContext) {
if let countForDates = CJDataItem.countForItemsByDate(with: context, with: Date(), andNumberOfDates: 7) {
cjCountItemsForDates = countForDates
}
}
}
Here is the simplified view:
struct CJReportsViewController: View {
@Environment(\.managedObjectContext) var managedObjectContext
@ObservedObject var dataSource: CJChartsDataDataSource
var body: some View {
/// ...
}
}
How do I respond to changes in this CJDataItem entity so that this ObservableObject gets updated, and so the SwiftUI view also gets the update?