Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to automatically update View Model when CoreData changes in SwiftUI?

Context

I have an App using SwiftUI and CoreData. For displaying the Data and updating it automatically when changes appear in the Model, SwiftUI provides the @FetchRequest Property Wrapper, that can be used in Views.

However, I would like to have a ViewModel that manages the Data stored in CoreData and can be used by Views through the @Published Property Wrapper. But I have difficulties implementing a solution, that also updates automatically to changes in CoreData.


Code

class SomeViewModel: ObservableObject {
    @Published var filteredEntities: [Entity]

    init() {
        // Load all Entities from CoreData, filter and assign them to filteredEntities.
        // Also make sure, that when CoreData changes, the step above gets repeated.
    }
}

Questions

  • Is this possible and was SwiftUI & MVVM designed for this?
  • How can I achieve the goal described above?
like image 408
christophriepe Avatar asked Oct 19 '25 10:10

christophriepe


1 Answers

There is no need for view model objects in SwiftUI. The View struct holds the view data and the property wrappers makes it behave like an object. This gives you the speed of value types with the benefits of reference types, i.e. best of both worlds. If you attempt to use your own view model object you'll run into the kind of object consistency issues that SwiftUI was designed to eliminate.

The property wrapper for core data is @FetchRequest

like image 153
malhal Avatar answered Oct 22 '25 03:10

malhal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!