ObervableObject being init multiple time, and not refreshing my view

后端 未结 1 592

i have a structure like that

contentView {
    navigationView{
     foreach {
        NavigationLink(ViewA(id: id))
     }
    }
}

///where

1条回答
  •  佛祖请我去吃肉
    2020-12-21 18:17

    There are two issues here:

    1. SwiftUI uses value types that that get initialized over and over again each pass through body.
    2. Related to #1, NavigationLink is not lazy.

    #1

    A new ListObj gets instantiated every time you call ViewA.init(...). ObservedObject does not work the same as @State where SwiftUI keeps careful track of it for you throughout the onscreen lifecycle. SwiftUI assumes that ultimate ownership of an @ObservedObject exists at some level above the View it's used in.

    In other words, you should almost always avoid things like @ObservedObject var myObject = MyObservableObject().

    (Note, even if you did @State var model = ListObj() it would be instantiated every time. But because it's @State SwiftUI will replace the new instance with the original before body gets called.)

    #2

    In addition to this, NavigationLink is not lazy. Each time you instantiate that NavigationLink you pass a newly instantiated ViewA, which instantiates your ListObj.

    So for starters, one thing you can do is make a LazyView to delay instantiation until NavigationLink.destination.body actually gets called:

    // Use this to delay instantiation when using `NavigationLink`, etc...
    struct LazyView: View {
        var content: () -> Content
        var body: some View {
            self.content()
        }
    }
    

    Now you can do NavigationLink(destination: LazyView { ViewA() }) and instantiation of ViewA will be deferred until the destination is actually shown.

    Simply using LazyView will fix your current problem as long as it's the top view in the hierarchy, like it is when you push it in a NavigationView or if you present it.

    However, this is where @user3441734's comment comes in. What you really need to do is keep ownership of model somewhere outside of your View because of what was explained in #1.

    0 讨论(0)
提交回复
热议问题