I have a Core Data model with an entity generated into class Task
. I am trying to get the Combine publisher objectWillChange
from the NSManagedObject
to send (automatically, without manual work), but it won't. The task entity has a name
attribute.
let task = Task(context: container.viewContext)
let taskSubscription = task.objectWillChange.sink(receiveValue: { _ in
print("Task changed")
})
task.name = "Foo" // WILL NOT trigger
If I call send manually, the subscription will work:
task.objectWillChange.send() // Will trigger
If I replace this with a simple ObservableObject
, it will work as expected:
class DummyTask: ObservableObject {
@Published var name: String?
}
let dummy = DummyTask()
let dummySubscription = dummy.objectWillChange.sink(receiveValue: { _ in
print("Dummy changed")
})
dummy.name = "Foo" // Will trigger
dummy.objectWillChange.send() // Will trigger
Is NSManagedObject bugged? How should I observe the general entity object for changes? How should I get SwiftUI to see them?
This is using Xcode 11.0 and iOS 13.
name
marked as Published? That's usually the cause when I have problems. I don't think that there is enough here for anyone to help you unfortunately. hackingwithswift.com/quick-start/swiftui/… or andrewcbancroft.com/blog/ios-development/data-persistence/… may help youname
in theNSManagedObject
is as it is generated from the model definition. When you look at the generated swift file, it is@NSManaged
. The point here is that these two work differently despite both beingObservableObject
s.@ObservedObject
and invokedobjectWillChange.send()
for the instance.