Replies: 3 comments 8 replies
-
Hi @twittemb, I don't know if I've seen this exact issue, but definitely there are lots of view configurations you can do that cause very weird things to happen. For example we have this UI test that shows how SwiftUI can write to a binding long after the view has gone away, and it's only reproducible with a hierarchy of That's the only concrete thing I can say, but if you can share more code so that I can reproduce this locally I'd be curious to see what is going on. |
Beta Was this translation helpful? Give feedback.
-
Thanks for you answer. here is a code that will demonstrate that: import SwiftUI
@main
struct MyApp: App {
var body: some Scene {
WindowGroup {
MainView(resolver: makeDependency)
}
}
}
func makeDependency() -> MyDependency {
print("makeDependency")
return MyDependency(value: "5")
}
class MyDependency: ObservableObject {
@Published
var value: String
init(value: String) {
self.value = value
}
}
struct MainView: View {
var resolver: () -> MyDependency
@State var text = ""
init(resolver: @escaping () -> MyDependency) {
self.resolver = resolver
}
var body: some View {
NavigationStack { // if commented, no double dep resolution
WithDependencyView(resolver: resolver) { dependency in
VStack {
Text(dependency.value)
TextField("Input", text: $text, axis: .horizontal) // if commented, no double dep resolution
}
}
}
}
}
// equivalent to WithViewStore
struct WithDependencyView<Content: View>: View {
@StateObject var dependency: MyDependency
let content: (MyDependency) -> Content
init(
resolver: @escaping () -> MyDependency,
@ViewBuilder content: @escaping (MyDependency) -> Content
) {
self._dependency = StateObject(wrappedValue: resolver())
self.content = content
}
var body: some View {
self.content(self.dependency)
}
} |
Beta Was this translation helpful? Give feedback.
-
Thanks a lot for all your nice answers. I assume it is a bug then. I'll try to fill a radar as well. I can't think of a workaround for now. I can't change my view hierarchy as the path of |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Hi
@mbrandonw I saw you were experimenting with @StateObject in
WithViewStore
.I’m my self playing with that (create a StateObject in an
init
) and I encountered a weird instantiation behaviour where the wrapped value could be created twice. It happens only if theView
(WithViewStore
in your case) is embedded in aNavigationStack
AND there is some state driven component inside theView
(WithViewStore
in your case).I ask the question because you might have the issue as well.
Here is what the code would look like (not my exact code per se but a simplified version for the sake of clarity).
Beta Was this translation helpful? Give feedback.
All reactions