Published and NSManaged

July 13, 2020 • 11:31 PM

While developing a universal app with the updated SwiftUI framework, I found that @Published decorators do not function as intended in objects inheriting from NSManagedObject class.

What’s Expected & What’s Broken

What’s exactly the expected behaviour anyway? We know that —

But here’s what is broken: Published variables in NSManagedObject instances do not update SwiftUI views as expected.

The Cause

As discussed on Stack Overflow, this is likely a bug on Apple’s end. There have been discussions since September 2019 but this problem still exists today. Somehow the implementation of ObservableObject protocol for NSManagedObject doesn’t trigger objectWillChange.send() method.

The Workaround

Since the objectWillChange.send() method doesn’t get triggered, the workaround is to simply trigger it manually.

Consult to Jesse Spencer’s answer in the same thread. Or the answer of Anthony’s.