【发布时间】:2020-07-08 23:34:31
【问题描述】:
代码在 Xcode 11.3 中运行,但更新到 11.4 后,我现在遇到两个错误:
环境中的上下文未连接到持久存储协调器。
线程 1:致命错误:未找到 UpdateTagView 类型的 ObservableObject。 UpdateTagView 的 View.environmentObject(_:) 作为该视图的祖先可能会丢失。
这就是我将对象添加到环境中的方式:
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
context.mergePolicy = NSMergeByPropertyStoreTrumpMergePolicy
let em = EventManager()
let tagger = UpdateTagView()
let contentView = ContentView()
.environment(\.managedObjectContext, context)
.environmentObject(em)
.environmentObject(tagger)
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIHostingController(rootView: contentView)
self.window = window
window.makeKeyAndVisible()
}
}
我用@EnvironmentObject 在视图中调用它们:
struct ViewName: View {
@EnvironmentObject var em: EventManager
@EnvironmentObject var tagger: UpdateTagView
以下是 ObservableObject 中的示例:
class UpdateTagView: ObservableObject {
@Published var counter: Int = 0
@Published var language: String = "English"
}
干杯~
【问题讨论】:
-
在 Xcode 11.4 (11E146) 上运行良好,刚刚创建项目并添加了您的代码。这似乎是由于不同的代码。
-
我在两台不同的笔记本电脑上尝试了这段代码,适用于 Xcode 11.3 但不适用于 11.4。我在 Xcode 11.4 上尝试了该项目的早期版本,它也有同样的错误。感谢您的检查。