1

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?

1
  • 1
    You need to do it manually by subscribing to and handling NSManagedObjectContext notifications, see for instance this article Commented Jul 10, 2022 at 6:49

1 Answer 1

1

ObservableObject is part of Combine framework usually we don't need that when using CoreData because we don't need CombineLatest etc.

You can simply initialize the @FetchRequest with a configured NSFetchRequest instance:

@FetchRequest(fetchRequest: request)
private var quakes: FetchedResults<Quake>

https://developer.apple.com/documentation/swiftui/fetchrequest

Note because NSFetchRequest is an object make sure to create it once somewhere and reuse it, don't create objects on demand or you'll get a SwiftUI memory leak.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.