Post

Replies

Boosts

Views

Activity

@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: 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: 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: 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
8
0
3.9k
Jul ’20