问题描述
我在 @ObservableObject 类中使用 @EnvironmentObject 时遇到问题。根据一些研究,这是不可能的,因为 EnvironmentObject 仅用于视图。
我已采取以下措施,但该值并未动态更新。
例如,它被初始化为“A”的值,但是当我在使用 EnvironmentObject 的类中更改值时,在我的 ObservableObject 类中找到的值仍然是“A”。它会在所有其他使用 @EnvironmentObject 的位置更新,而不是 ObservableObject API 类。
当 EnvironmentObject 更新发布的变量时,有没有办法让 ObservableObject API 类中的代码更新?
需要在其中运行类似于 EnvironmentObject 的变量的类是 API 类。
class SelectedStation: ObservableObject {
@Published var selectedStation: String = "A"
}
class API: ObservableObject {
var selectedStation: SelectedStation
init(selectedStation: SelectedStation) {
self.selectedStation = selectedStation
print(selectedStation.selectedStation)
}
///some code that will utilize the selectedStation variable
}
我到底做错了什么?
解决方法
您正在初始化不同版本的类。尝试像这样添加 public static let shared = SelectedStation()
:
class SelectedStation: ObservableObject {
@Published var selectedStation: String = "A"
public static let shared = SelectedStation()
}
然后在需要使用的地方,声明为:
var selectedStation = SelectedStation.shared
此外,您应该将@Published var 重命名为 selectedStation 以外的其他名称,否则您可能会遇到不幸的 selectedStation.selectedStation
作为对该变量的引用。
最后,请记住 @Environment
需要使用 SelectedStation.shared
进行初始化,因此所有内容都共享该类的一个实例。