我试图更好地理解@EnvironmentObject,所以我在下面编写了示例代码来复制我面临的问题
这是我在其中声明需要在多个位置访问并在ContentView中显示和更新的数组的类
class User: ObservableObject {
@Published var array = [String]()
func diplayName(name: String){
self.array.append(name)
}
}
我希望能够将我的数组附加到另一个类中。类似于以下代码
class myTests: ObservableObject {
@EnvironmentObject var user:User
func diplayMyName(name: String){
self.user.array.append(name)
}
}
当我在myTests类中调用displayMyName函数时,出现如下错误消息
Fatal error: No ObservableObject of type User found.
A View.environmentObject(_:) for User may be missing as an ancestor of this view.
这是我的contentView的样子
struct ContentView: View {
@EnvironmentObject var user:User
var testing = myTests()
var body: some View {
VStack {
List(user.array, id: \.self){ x in
Text(x)
}
Button(action: {
self.user.diplayName(name: "Name1")
// self.testing.diplayMyName(name: "Name2")
}){
Text("Call Function")
}
}
}
}
这就是我在场景委托中声明我的环境对象的方式
let contentView = ContentView().environmentObject(User())
如果有人可以帮助我理解为什么从myTests类追加已发布的数组时出现错误,我将非常感谢。谢谢。
要解决我的问题,我做了以下调整 我在myTests类中返回了一个数组
class myTests {
var ar = [String]()
func displayMyName() -> [String] {
ar.removeAll()
ar.append(contentsOf: ["Name2", "Name3"])
return ar
}
}
并将其添加到ContentView中的数组
struct ContentView: View {
@EnvironmentObject var user : User
var testing = myTests()
var body: some View {
VStack {
List(user.array, id: \.self){ x in
Text(x)
}
Button(action: {
self.user.array.append(contentsOf: self.testing.displayMyName())
}){
Text("Call Function")
}
}
}
}