从 UIKit 或 SKScene 很容易观察 ObservedObject 的变化。下面的示例来自 UIViewController,将其更改为等效于 SKScene:
import Combine
class Object: ObservableObject {
@Published var value: Int = 10
@Published var anotherValue: String = "Hello"
}
class MyViewController: UIViewController {
let observedObject = Object()
var cancellableBag = Set<AnyCancellable>()
override func viewDidLoad() {
super.viewDidLoad()
// REACT TO ANY @PUBLISHED VARIABLE
observedObject.objectWillChange.sink {
// Do what you want here
}.store(in: &cancellableBag)
// REACT ONLY TO ONE SPECIFIED @PUBLISHED VARIABLE
observedObject.$value.sink { value in
// Do what you want here
}.store(in: &cancellableBag)
}
}
请注意,这@Published
是一个propertyWrapper
with projectedValue
。在projectedValue
这种情况下Publisher
, 每次wrappedValue
更改时都会发出事件,因此为了访问projectedValue
有必要调用$value
而不是value
.