将 Observable 对象的通知更改为 SwiftUI 中的嵌套对象

2024-03-30

我有以下场景。

我有 AppState,它由 Foo 类型的对象组成。 Foo 有一个计数器变量,我想在计数器值更新时调用 objectWillChange,这样我就可以更新 UI。

目前什么也没有发生。增量函数被调用,但 UI 永远不会更新。




import Foundation
import Combine

class Foo: ObservableObject {
    @Published var counter: Int = 999
    
    func increment() {
        counter += 1 // how to get notified when counter value changes
    }
}

class AppState: ObservableObject {
    
    @Published var foo: Foo = Foo()
}

// usage in Scene Delegate as Environment Object
let appState = AppState()

// Use a UIHostingController as window root view controller.
if let windowScene = scene as? UIWindowScene {
    let window = UIWindow(windowScene: windowScene)
    window.rootViewController = UIHostingController(rootView: accountSummaryScreen.environmentObject(appState))

UPDATE

class Foo: ObservableObject {
    @Published var counter: Int = 999 {
        didSet {
            objectWillChange.send() 
        }
    }
    
    func increment() {
        counter += 1 // how to get notified when counter value changes
    }
}


未检测到更改,因为Foo,作为引用类型,实际上并没有改变 - 它是相同的引用,所以@Published在这里没有帮助。

AppState需要手动订阅更改并调用自己的更改objectWillChange.send:

class AppState: ObservableObject {
    
    var foo: Foo = Foo() {
       didSet {
          cancellables = []
          foo.$counter
             .map { _ in } // ignore actual values
             .sink(receiveValue: self.objectWillChange.send)
             .store(in: &cancellables)
       }
    }

    private var cancellables: Set<AnyCancellable> = []
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将 Observable 对象的通知更改为 SwiftUI 中的嵌套对象 的相关文章

随机推荐