NSManagedObject does not update SwiftUI view

NSManagedObject is a subclass of ObservableObject and is a publisher acccording to 10:13 of WWDC19-230 so it’s expected that it will publish attributes changes and trigger the SwiftUI view updates.


However in the following snippet the TextField.disabled never gets updated, even though managedEntity.enabled attribute changed on the line 10 with the Toggle.


@objc(ManagedEntity) public class ManagedEntity: NSManagedObject {
    @NSManaged public var name: String // = "Managed Entity"
    @NSManaged public var enabled: Bool // = false
}

struct ContentView: View {
    @ObservedObject var managedEntity: ManagedEntity
    var body: some View {
        VStack {
            Toggle("ManagedEntity enabled", isOn: $managedEntity.enabled)
            TextField("ManagedEntity name", text: $managedEntity.name)
                .disabled(!managedEntity.enabled)
        }
    }
}


The same pattern works if I use my own subclass of ObservableObject with @Published attributes, also I see NSManagedObjects publishers update assigned UIKit views, but not the SwiftUI.


I'm afraid I might be missing some important basics about using Core Data with SwiftUI so would highly appreciate any help or reference.


Thanks!

Accepted Reply

Just got help through Twitter: https://twitter.com/konstantinbe/status/1166423609348427778?s=20

Thanks a lot!


The solution is to override willChangeValue of NSManagedObject subclass and send the publisher manually. It helps now, hope it will be automatic future:


override public func willChangeValue(forKey key: String) {
        super.willChangeValue(forKey: key)
        self.objectWillChange.send()
    }

Replies

Just got help through Twitter: https://twitter.com/konstantinbe/status/1166423609348427778?s=20

Thanks a lot!


The solution is to override willChangeValue of NSManagedObject subclass and send the publisher manually. It helps now, hope it will be automatic future:


override public func willChangeValue(forKey key: String) {
        super.willChangeValue(forKey: key)
        self.objectWillChange.send()
    }

Can you please explain how to trigger it?