@Published property inside an NSManagedObject doesn't trigger view updates

Viewed 280

I have a Core Data data model that I use in my app, and would like to add a property to that data model that I don't necessarily want to store, so instead of @NSManaged I made that property @Published.

 @Published var currentTime = "00:00"

And in the view instances I, of course, use an @ObservedObject

 @ObservedObject var timeItem: TimeItem

And in that view, I use a timer to update that value

.onReceive(Timer.publish(every: 0.015, on: .main, in: .common).autoconnect()) { time in
     timeItem.currentTime = timeItem.timeFinished.timeIntervalSince(Date()).editableStringMilliseconds()
 }

However, that doesn't trigger the view updates. I'm not sure if NSManagedObject is to blame, but if I replace that timeItem.currentTime value with a local @State one, everything works.

@State private var currentTime: String = "00:00"

Any ideas fellas?

1 Answers

It's seems that there is a bug here or whatever it is. I had the same problem. To solve this issue you must trigger publisher manually:

 @Published var currentTime = "00:00" {
     willSet {
         objectWillChange.send()
     }
 }

At this moment you even don't need @Published wrapper.

To trigger update of @NSManaged properties you can override willChangeValue method.

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

I hope Apple will fix this strange behaviour as soon as possible.

Related