简体   繁体   中英

StateObject property doesn't update view but ObservedObject does

I am saving data to Realm DB in another View where I use @EnvironmentObject var modelData: DBViewModel and loading them in this View

struct SelectedSinsList: View {
@StateObject var modelData = DBViewModel() //@ObservedObject works, as it always recreates the List when I open this view and values are updated
var body: some View {
    NavigationView {
        ScrollView{
            VStack(spacing: 15){
                ForEach(modelData.sins){sin in //..........

That behavior indicates that the only reason your view is updating with new data is that a parent view is redrawing, thus triggering the "unowned" observed object to be rebuilt.

State and StateObject outlast the View struct's body being invalidated and redrawn. To use those, you'll need to connect the callback or publisher in the StateObject to its objectWillChange publisher by calling self.objectWillChange.send()

But if that DBViewModel is already an environmentObject, why recreate it?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM