Swiftui:MacOS App:在 ContentView 中获取核心数据 OK,但是如何使用 AppDelegate 的结果?

Swifui: MacOS App: Fetching Core Data in ContentView OK, but how to use the result from AppDelegate?

使用 Xcode 11.6 (11E708),SwiftUI,对于 MacOS 应用程序,我在 ContentView.swift 中生成了数据。但是我不能在 AppDelegate.swift:

中使用这些数据

构建成功但 print(contentView.order.item)(请参阅下文)生成此消息:

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

我错过了什么?

在ContentView.swift中:

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

在AppDelegate.swift中:

func applicationDidFinishLaunching(_ aNotification: Notification) {
    ... 
    let contentView = ContentView()
    print(contentView.order.item)
    ...

如果要将其用作 @EnvironmentObject,您需要将 Order 注入环境:

let order = Order() // declare it once
let contentView = ContentView().environmentObject(order) // inject to the environment