gpt4 book ai didi

ios - @Published 属性包装器不适用于 ObservableObject 的子类

转载 作者:行者123 更新时间:2023-11-28 05:39:00 25 4
gpt4 key购买 nike

我有一个符合@ObservableObject 协议(protocol)的类,并使用它自己的变量从它创建了一个子类,并使用@Published 属性包装器来管理状态。

似乎在使用子类时忽略了@published 属性包装器。有谁知道这是否是预期的行为,是否有解决方法?

我正在运行 iOS 13 Beta 8 和 xCode Beta 6。

这是我所看到的示例。在 MyTestObject 上更新 TextField 时,Text View 会使用 aString 值正确更新。如果我更新 MyInheritedObjectTextField,则 TextView 中的 anotherString 值不会更新。

import SwiftUI

class MyTestObject: ObservableObject {
@Published var aString: String = ""

}

class MyInheritedObject: MyTestObject {
@Published var anotherString: String = ""
}

struct TestObserverWithSheet: View {
@ObservedObject var myTestObject = MyInheritedObject()
@ObservedObject var myInheritedObject = MyInheritedObject()

var body: some View {
NavigationView {
VStack(alignment: .leading) {
TextField("Update aString", text: self.$myTestObject.aString)
Text("Value of aString is: \(self.myTestObject.aString)")

TextField("Update anotherString", text: self.$myInheritedObject.anotherString)
Text("Value of anotherString is: \(self.myInheritedObject.anotherString)")
}
}
}
}

最佳答案

终于找到了这个问题的解决方案/解决方法。如果您从子类中删除属性包装器,并在变量上调用基类 objectWillChange.send(),则状态会正确更新。

注意:不要重新声明 let objectWillChange = PassthroughSubject<Void, Never>()在子类上,因为这将再次导致状态无法正确更新。

我希望这会在未来的版本中作为 objectWillChange.send() 得到修复。有很多样板需要维护。

这是一个完整的示例:

    import SwiftUI

class MyTestObject: ObservableObject {
@Published var aString: String = ""

}

class MyInheritedObject: MyTestObject {
// Using @Published doesn't work on a subclass
// @Published var anotherString: String = ""

// If you add the following to the subclass updating the state also doesn't work properly
// let objectWillChange = PassthroughSubject<Void, Never>()

// But if you update the value you want to maintain state
// of using the objectWillChange.send() method provided by the
// baseclass the state gets updated properly... Jaayy!
var anotherString: String = "" {
willSet { self.objectWillChange.send() }
}
}

struct MyTestView: View {
@ObservedObject var myTestObject = MyTestObject()
@ObservedObject var myInheritedObject = MyInheritedObject()

var body: some View {
NavigationView {
VStack(alignment: .leading) {
TextField("Update aString", text: self.$myTestObject.aString)
Text("Value of aString is: \(self.myTestObject.aString)")

TextField("Update anotherString", text: self.$myInheritedObject.anotherString)
Text("Value of anotherString is: \(self.myInheritedObject.anotherString)")
}
}
}
}

关于ios - @Published 属性包装器不适用于 ObservableObject 的子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57615920/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com