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
SwiftUI
& MVVM
designed for this?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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With