1

我有这样ObservableObject的情况,我通过使用environmentObject().

class MenuModel: ObservableObject {

    @Published var selection: Int = 0
    @Published var isMenuOpen: Bool = false

    @Published var tabItems : [TabItem] = [TabItem]()
//    {
//        didSet {
//            objectWillChange.send()
//        }
//    }
    @Published var menuItems : [MenuItem] = [MenuItem]()
//    {
//        didSet {
//            objectWillChange.send()
//        }
//    }

    //var objectWillChange = PassthroughSubject<Void, Never>()
}

以下是我不太了解的问题: 1. 上面的代码可以正常工作,因为所有属性都是@Published。2. 但是如果我把它改成这样

class Click5MenuModel: ObservableObject {

    @Published var selection: Int = 0
    @Published var isMenuOpen: Bool = false

    var tabItems : [TabItem] = [TabItem]()
    {
        didSet {
            objectWillChange.send()
        }
    }
    var menuItems : [MenuItem] = [MenuItem]()
    {
        didSet {
            objectWillChange.send()
        }
    }

    var objectWillChange = PassthroughSubject<Void, Never>()
}

然后@Published 属性停止刷新依赖于这个 ObservableObject 的视图!这是为什么。我也尝试添加didSetobjectWillChange.send()但这也会导致一些奇怪的行为,并且代码有点尴尬。

这是否意味着我只能使用@PublishedONLY objectWillChange方法?

4

1 回答 1

1

默认实现才有效(只要您有 @Published 属性)。这是来自API声明:

/// By default an `ObservableObject` will synthesize an `objectWillChange`
/// publisher that emits before any of its `@Published` properties changes:
...
@available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)
extension ObservableObject where Self.ObjectWillChangePublisher == ObservableObjectPublisher {

    /// A publisher that emits before the object has changed.
    public var objectWillChange: ObservableObjectPublisher { get }
}

所以删除以下内容:

var objectWillChange = PassthroughSubject<Void, Never>()

并使用

didSet {
    self.objectWillChange.send()
}
于 2019-11-26T13:35:21.320 回答