简体   繁体   English

SwiftUI:对 SwiftUI 视图中的 NSManagedObject 属性更改做出反应?

[英]SwiftUI: react to NSManagedObject property change in SwiftUI view?

I am trying to figure how to have a SwiftUI view properly react to the changes made to an NSManagedObject property.我想弄清楚如何让 SwiftUI 视图正确地对 NSManagedObject 属性所做的更改做出反应。

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 可以让我在 Car 实体上设置sold属性。

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:切换控件确实会在 car 实例上设置sold属性,但是,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.然后我实现了接收sink逻辑,然后在 model 上设置已发布的sold属性。因此汽车上的sold属性由切换设置,接收器启动并设置 model.sold,然后切换 label 文本确实更新.

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?我怎样才能去掉 model 中的附加@Published var sold:Bool = false并简单地使 Toggle label 对实际的car.sold属性做出反应?

Observe Car directly, it confirms to ObservableObject, so instead of view model pass in view it like直接观察 Car,它确认到 ObservableObject,所以而不是视图 model 传递视图

struct CarView: View {
  @ObservedObject var car: Car

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM