0

I trimmed things down to this very simple example (a vanilla SwiftUI project, edit only ContentView and one line in SceneDelegate). Sets up a trivial ObservableObject and a couple of Views for screens. With latest Xcode 11.4 and simulator crashes very easily.

import SwiftUI

// NB In SceneDelegate added: let contentView = ContentView().environmentObject(EO())
class EO: ObservableObject {
    @Published var n = 2
}

struct ContentView: View {
    @EnvironmentObject var eo: EO

    var body: some View {
        NavigationView {
            VStack {
                Text("A: \(eo.n)")
                NavigationLink(destination: ContentViewB()) {
                    Text("Go to B")
                }
            }
        }
    }
}

struct ContentViewB: View {
    @EnvironmentObject var eo: EO
    var body: some View {
        VStack {
            Text("B: \(eo.n)")
        }.onAppear {
            self.eo.n += 1
        }
    }
}

Am I doing something wrong? Or is this a SwiftUI bug? It seems to work fine initially then on re-navigating to child view it crashes. Though the exact behaviour is non deterministic (might crash on 2nd or 3rd navigation!)

James
  • 1,985
  • 18
  • 19
  • So it crashes on navigation to ContentViewB? Likely duplicate of https://stackoverflow.com/questions/57582813/swiftui-thread-1-fatal-error-no-observable-object-of-type-myobject-type-fou - you are not passing the environment to the `destination`. – matt Apr 03 '20 at 21:29
  • Yes, ContentView works fine/displays updated value. – James Apr 03 '20 at 21:31
  • 1
    I'm surprised it was working before at all; it sounds like there was a bug previously. :) Crashing is correct behavior. You need to say `destination: ContentViewB().environmentObject(self.eo)`. – matt Apr 03 '20 at 21:32
  • Oh, is that required? ContentViewB will be a child of ContentView which has the environmentObject set. – James Apr 03 '20 at 21:41
  • Yeah I don't think that should be required https://www.hackingwithswift.com/quick-start/swiftui/how-to-use-environmentobject-to-share-data-between-views However, it does stop it crashing in the simulator! So thank you! On device the original approach works fine. Wondering if somehow setting this explicitly works around an underlying bug? – James Apr 03 '20 at 21:46
  • You could be right. File a bug! Meanwhile you have your workaround. – matt Apr 03 '20 at 21:51

0 Answers0