This is how the crash looks like
So it randomly crashes on the UIKit line
UIKitCore
-[UIViewController _ancestorViewControllerOfClass:allowModalParent:] + 44
I have View in default SwiftUI navigation stack:
struct MyView: View {
@EnvironmentObject var viewModel: MyViewModel
@Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
var body: some View {
ZStack {
......
}
.onAppear {
self.viewModel
.onViewAppear(presentationMode: self.presentationMode)
}
}
}
final class MyViewModel {
var presentationMode: Binding<PresentationMode>?
func onViewAppear(presentationMode: Binding<PresentationMode>) {
self.presentationMode = presentationMode
}
func hide() {
presentationMode?.wrappedValue.dismiss() // crashes after calling this
}
}
So I push MyView in navigation stack this way:
NavigationLink(
destination: MyView()
) {
Image(systemName: "plus.circle")
.font(.title)
}
And then after user presses a button in MyView after several seconds I call hide()
in the MyViewModel. Almost all the time it works but in 5-10% cases it crashes.
MyView().environmentObject(viewModel)
? Seems like the view model wouldn't be set in that initialiser. – Responser@StateObject
instead of@EnvironmentObject
? Maybe worth a try, this definitely seems like a SwiftUI bug though! – Responser@EnvironmentObject var viewModel: MyViewModel
to@StateObject var viewModel: MyViewModel = MyViewModel()
– Responser