Fixing NSManagedObject’s ObservableObject conformance

In working with SwiftUI you may have noticed that NSManagedObject is not a particularly correct implementation of ObservableObject. Your NSManagedObject does not publish changes when any of its @NSManaged properties are mutated.

There’s an easy fix for this:

open class ManagedObject: NSManagedObject {
    override public func willChangeValue(forKey key: String) {
        super.willChangeValue(forKey: key)

        objectWillChange.send()
    }
}

Simply tweak your model classes to inherit from ManagedObject, instead of NSManagedObject, et voilà  - your managed objects will behave as expected.

Explanation #

This essentially hooks into a core NSManagedObject method - willChangeValue(forKey:) and overrides it to also publish changes to the objectWillChange publisher when invoked.

 
8
Kudos
 
8
Kudos

Now read this

Removing List’s cell separators in SwiftUI

Currently, as of Xcode 11.1, Apple provides no way for developers to specify a cell separator style for SwiftUI’s List. Having run into this issue myself, I finally stumbled upon a workaround: UITableView.appearance().separatorStyle =... Continue →