Using SwiftUI, Core Data, and one-to-many relationships, why does the list not update when adding a row on the Many side

后端 未结 3 1989
我在风中等你
我在风中等你 2021-01-22 12:18

I have a SwiftUI project with Core Data. The data model is a simple one-to-many and two primary views which each have a textfield at the top and a button to add a new item to th

3条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-22 13:16

    After more research, ObservableObject has a built-in publisher by default that can notify any views that the object will change. Simply call

    objectWillChange.send()
    

    on an ObservableObject before changes occur to have any UI refresh that is observing that object.

    For example, to fix my issue where changes to Core Data relationships weren't updating the UI, I've added this call before saving the context.

    if workContext.hasChanges {
        objectWillChange.send()
        do {
            try self.workContext.save()
        } catch {
            fatalError(error.localizedDescription)
        }
    }
    

    No need to implement a custom @Published property or other workaround.

提交回复
热议问题