Warm tip: This article is reproduced from stackoverflow.com, please click
combine swiftui xcode11

Xcode 11 beta 3 crashing when using NavigationLink, @EnvironmentObject and List together

发布于 2020-03-27 10:19:40

I've got a strange crash in SwiftUI / Xcode 11 beta 3 with code like the one below (I've kept only the bare minimum to show the behavior):

import SwiftUI
import Combine

final class AppData: BindableObject  {
    let didChange = PassthroughSubject<AppData, Never>()

    init() { }
}

struct ContentView : View {
    var body: some View {
        NavigationView {
            NavigationLink(destination: DetailView() ) {
                Text("link")
            }
        }
    }
}

struct DetailView : View {
    @EnvironmentObject var appData: AppData
//  @ObjectBinding var appData = AppData() -> Works 

    var body: some View {
        List {
            Text("A")
            Text("B")
            Text("C")
        }
    }
}

The BindableObject is injected in SceneDelegate.swift like this:

....
        // Use a UIHostingController as window root view controller
        if let windowScene = scene as? UIWindowScene {
            let window = UIWindow(windowScene: windowScene)
            window.rootViewController = UIHostingController(rootView: ContentView()
                                           .environmentObject(AppData()))
            self.window = window
            window.makeKeyAndVisible()
        }
....

When following the NavigationLink it crashes with

Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)

If I remove the List view from the detail view it works OK. The same if I use @ObjectBinding instead (like in the commented line in my code).

The same code used to work in previous betas.

Questioner
Bogdan Farca
Viewed
136
Sam Rayner 2019-07-04 22:36

It's a bug in Xcode 11 beta 3. The old behaviour will likely return.

From https://developer.apple.com/tutorials/swiftui/handling-user-input as of July 4th 2019:

Step 4

In Xcode 11 beta 3, the LandmarkDetail view doesn’t automatically access the UserData object in the view hierarchy’s environment. The workaround for this is to add the environmentObject(_:) modifier to the LandmarkDetail view.