Swiftui:对SwiftUi视图中的NSManageBject属性的反应?
我试图弄清楚如何使SwiftUI视图适当地对NSManageBject属性所做的更改做出反应。
示例:
class MyViewModel: ObservableObject {
@Published var car:Car // <-- NSManagedObject
@Published var sold:Bool = false // <-- I don't want to do this, I want to simply observe the sold property on car and not have to implement this sink logic below
var subs = [AnyCancellable]()
init(car:Car) {
self.car = car
self.sold = car.sold
self.car.publisher(for: \.sold)
.removeDuplicates()
.receive(on: RunLoop.main)
.sink { [weak self] sold in
self?.sold = sold
}
.store(in: &subs)
}
}
例如,我有一个切换,可以让我在汽车实体上设置属性。
Toggle(isOn: Binding<Bool>(get: { model.car.sold }, set: { model.car.sold = $0 } )) {
if model.car.sold {
Text("ON")
} else {
Text("OFF")
}
}
切换控件确实设置了已在汽车实例上出售的
属性,但是,切换标签:
if model.car.sold {
Text("ON")
} else {
Text("OFF")
}
不会相应地更新。
因此,如果我整体上更改汽车实体,则更新事物,如果我更改实体的属性,则视图不会更新。因此,我实现了sink
逻辑,然后在模型上设置已发布的出售
属性。因此,出售的汽车上的属性是由切换设置的
属性。
我应该如何消除售出的其他@pstarmed var:bool = false
在模型中,简单地导致切换标签对实际car.sold.sold
属性做出反应?
I am trying to figure how to have a SwiftUI view properly react to the changes made to an NSManagedObject property.
Example:
class MyViewModel: ObservableObject {
@Published var car:Car // <-- NSManagedObject
@Published var sold:Bool = false // <-- I don't want to do this, I want to simply observe the sold property on car and not have to implement this sink logic below
var subs = [AnyCancellable]()
init(car:Car) {
self.car = car
self.sold = car.sold
self.car.publisher(for: \.sold)
.removeDuplicates()
.receive(on: RunLoop.main)
.sink { [weak self] sold in
self?.sold = sold
}
.store(in: &subs)
}
}
As an example, I have a Toggle that lets me set the sold
property on the Car entity.
Toggle(isOn: Binding<Bool>(get: { model.car.sold }, set: { model.car.sold = $0 } )) {
if model.car.sold {
Text("ON")
} else {
Text("OFF")
}
}
Toggling the control does set the sold
property on the car instance, but, the Toggle label:
if model.car.sold {
Text("ON")
} else {
Text("OFF")
}
does not update accordingly.
So, if I change the car entity as a whole, things update, if I change a property of the entity the view does not update. So then I implemented the sink
logic to then set a published sold
property on the model. So the sold
property on the car is set by the toggle, the sink kicks in and sets the model.sold, and then the Toggle label Text does update.
How can I do away with the additional @Published var sold:Bool = false
in the model and simply cause the Toggle label to react to the actual car.sold
property?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
直接观察汽车,它确认可观察到可观察的对象,因此不要像视图模型一样。
Observe Car directly, it confirms to ObservableObject, so instead of view model pass in view it like