参考URL: Swift4のKVOに感動した。
WKWebView Progress(Swift4)
import UIKit
class ViewController: UIViewController {
private var observers: [NSKeyValueObservation] = []
private let kvo = KVOSample()
override func viewDidLoad() {
super.viewDidLoad()
observers.append(kvo.observe(\.value, options: [.new, .old]){_ ,change in
print("new =",change.newValue ?? "")
print("old =", change.oldValue ?? "")
})
}
@IBAction func up(_ sender: UIButton) {
kvo.value += 1
}
// KVO Remove
@IBAction func removeKVO(_ sender: UIButton) {
observers.forEach { $0.invalidate() }
observers.removeAll()
}
}
// KVO Class
class KVOSample: NSObject{
// 監視プロパティ
@objc dynamic var value:Int = 0
}