This looks like a SwiftUI bug, but maybe I'm doing something wrong.
The documentation for @StateObject says: "SwiftUI creates a new instance of the object only once for each instance of the structure that declares the object. "
However, in some cases a @StateObject can be initialized more than once.
For example, this view:
when pushed onto a NavigationView using a NavigationLink inside a List, like this:
The output produced is:
As you can see, the SomeState initializer was called twice, when according to the documentation it should only be called once.
If you don't wrap the NavigationLink in a List:
Then the output is
Which is as expected.
I have also seen a similar case where onAppear also gets called twice for what should be only one instance of a view
The documentation for @StateObject says: "SwiftUI creates a new instance of the object only once for each instance of the structure that declares the object. "
However, in some cases a @StateObject can be initialized more than once.
For example, this view:
Code Block struct DetailView: View { @StateObject private var someState = SomeState() var body: some View { Group { Text("Detail view") } .navigationTitle("Detail View") .onAppear { logger.debug("On Appear") } } } class SomeState: ObservableObject { init() { logger.debug("init") } }
when pushed onto a NavigationView using a NavigationLink inside a List, like this:
Code Block struct ContentView: View { var body: some View { NavigationView { List { NavigationLink(destination: DetailView() ) { Text("Hello World") } } }.navigationViewStyle(DoubleColumnNavigationViewStyle()) } }
The output produced is:
[app] init
[app] On Appear
[app] init
As you can see, the SomeState initializer was called twice, when according to the documentation it should only be called once.
If you don't wrap the NavigationLink in a List:
Code Block var body: some View { NavigationView { NavigationLink(destination: DetailView() ) { Text("Hello World") } }.navigationViewStyle(DoubleColumnNavigationViewStyle()) }
Then the output is
[app] init
[app] On Appear
Which is as expected.
I have also seen a similar case where onAppear also gets called twice for what should be only one instance of a view