@StateObject is initialized twice for the same view instance?

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:

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
I have the same issue. did you find a solution for that bug?
This is fixed in beta 4
I’m having this issue in the iOS 14 GM.
XCode 12.3 (12C33), iOS 14.3

Issue still exists. Even a @StateObject in the ListView will get init() twice in the following simple scenario:

Code Block swift
struct ListView: View {
  @StateObject var viewModel = MyViewModel()
...
}


Code Block swift
NavigationView {
  ListView()
  DetailView(item: nil)
}.navigationViewStyle(DoubleColumnNavigationViewStyle())


Xcode 12.5 beta 3 (12E5244e), iOS 14.5 beta 3

Issue still exists.

I still see the issue in Xcode 12.5 beta 3 as well.

I see both a @StateObject initialized twice and onAppear called twice.

FYI this has been fixed in release version of 12.5

Still experiencing this issue in Xcode 14, iOS 15.x Simulators. Xcode 14 and iOS 16 it seems to be fixed.

@StateObject is initialized twice for the same view instance?
 
 
Q