我在环境对象符合定义了需要发布的变量的协议的视图中使用@EnvironmentObject。 当MyView在单独的文件中时,发生崩溃。当所有代码都在SceneDelegate文件中时,不会发生崩溃。有人可以确认相同的行为吗?这种行为是非常意外的。
有人知道如何解决此问题吗?
此代码重现了问题:
//MyView.swift
import SwiftUI
import Combine
struct MyView: View {
@EnvironmentObject var viewModel: MyViewModel
var body: some View {
VStack {
if self.viewModel.someText == nil { //<--Thread 1: EXC_BAD_ACCESS
Text("nil")
} else {
Text("not nil")
}
}
}
}
//SceneDelegate.swift
import SwiftUI
import Combine
class MyViewModel: ObservableObject & HasText {
@Published var someText: String?
var someTextPublished: Published<String?> { _someText }
var someTextPublisher: Published<String?>.Publisher { $someText }
init() {}
}
protocol HasText: AnyObject {
var someText: String? { get set }
var someTextPublished: Published<String?> { get }
var someTextPublisher: Published<String?>.Publisher { get }
}
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
let viewModel = MyViewModel()
let contentView = MyView().environmentObject(viewModel)
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIHostingController(rootView: contentView)
self.window = window
window.makeKeyAndVisible()
}
}