6

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
  • Does your Object implement ObservableObject ? Commented Dec 23, 2020 at 16:49

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

It is strongly discouraged to override willChangeValue method here. developer.apple.com/documentation/coredata/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.