1

With Xcode 11.6 (11E708), SwiftUI, for a MacOS app, I have data generated in the ContentView.swift. But I cannot use those data inside the AppDelegate.swift:

Build Succeeded but the print(contentView.order.item) (please see below) produce this message:

Thread 1: Fatal error: No ObservableObject of type Order found. A View.environmentObject(_:) for Order may be missing as an ancestor of this view.

What am I missing?

In ContentView.swift:

import SwiftUI
public class Order: ObservableObject {
    @Published var item = "Hello"
}
...
@EnvironmentObject var order: Order
...

In AppDelegate.swift:

func applicationDidFinishLaunching(_ aNotification: Notification) {
    ... 
    let contentView = ContentView()
    print(contentView.order.item)
    ...
pawello2222
  • 46,897
  • 22
  • 145
  • 209
kali mera
  • 13
  • 4

1 Answers1

0

You need to inject Order to the environment if it will be used as an @EnvironmentObject:

let order = Order() // declare it once
let contentView = ContentView().environmentObject(order) // inject to the environment
pawello2222
  • 46,897
  • 22
  • 145
  • 209