Reputation: 461
I'm using the new NavigationLink
in iOS 16 and hitting a problem where the target of the .navigationDestination
is being called twice. Example code:
struct Content: View {
var body: some View {
NavigationStack {
ScrollView {
VStack {
ForEach(0..<10) { number in
NavigationLink(value: number) {
Text("\(number)")
}
}
}
}.navigationDestination(for: Int.self) { value in
SubView(model: Model(value: value))
}
}
}
}
class Model: ObservableObject {
@Published var value: Int
init(value: Int) {
print("Init for value \(value)")
self.value = value
}
}
struct SubView: View {
@ObservedObject var model: Model
var body: some View {
Text("\(model.value)")
}
}
When I touch one of the numbers in the Content
view the init
message in the model is shown twice, indicating that the class has been instantiated more than once. This is not a problem in a trivial example like this, but in my app the model does a network fetch and calculation so this is being done twice, which is more of an issue.
Any thoughts?
Upvotes: 6
Views: 1063
Reputation: 303
I think problem is caused by ObservableObject. It needs to store it's state. I think it's better to use StateObject. Please try that one for SubView. :)
struct SubView: View {
@StateObject private var model: Model
init(value: Int) {
self._model = StateObject(wrappedValue: Model(value: value))
}
var body: some View {
Text("\(model.value)")
}
}
Upvotes: 1