Change to @Published var in @EnvironmentObject not reflected immediately

前端 未结 3 1303
臣服心动
臣服心动 2020-12-01 21:54

In this specific case, when I try to change an @EnvironmentObject\'s @Published var, I find that the view is not invalidated and updated immediatel

相关标签:
3条回答
  • 2020-12-01 22:31

    In Xcode 11 GM2, If you have overridden objectWillChange, then it needs to call send() on setter of a published variable.

    If you don't overridden objectWillChange, once the published variables in @EnvironmentObject or @ObservedObject change, the view should be refreshed. Since in Xcode 11 GM2 objectWillChange already has a default instance, it is no longer necessary to provide it in the ObservableObject.

    0 讨论(0)
  • 2020-12-01 22:34

    Changing

    final class UserData: NSObject, ObservableObject  {
    

    to

    final class UserData: ObservableObject  {
    

    does fix the issue in Xcode11 Beta6. SwiftUI does seem to not handle NSObject subclasses implementing ObservableObject correctly (at least it doesn't not call it's internal willSet blocks it seems).

    0 讨论(0)
  • 2020-12-01 22:47

    A couple of things.

    • Your setup doesn't work if you move the Button into MasterView either.
    • You don't have a import Combine in your code (don't worry, that alone doesn't help).

    Here's the fix. I don't know if this is a bug, or just poor documentation - IIRC it states that objectWillChange is implicit.

    Along with adding import Combine to your code, change your UserData to this:

    final class UserData: NSObject, ObservableObject  {
        var objectWillChange = PassthroughSubject<Void, Never>()
        @Published var changeView: Bool = false {
            willSet {
                objectWillChange.send()
            }
        }
    }
    

    I tested things and it works.

    0 讨论(0)
提交回复
热议问题