LoginSignup
3
5

More than 3 years have passed since last update.

Swift4のKVOを理解する

Posted at

はじめに

Swift4からKVOのやり方が変わったので備忘録です。

Objective-CまではNSStringでキー名を渡していたので、間違いが発生しやすかったです。
Swift4からはKeyを\を使用して表現できるため、コンパイラチェックの恩恵が受けられるようになりました。

サンプルコード

ObservedObject.swift
class ObservedObject: NSObject {

    @objc dynamic var count: Int = 0

    func start() {
        Time.scheduledTimer()
    }

    @objc func addCount(_ sender: Timer) {
        count += 1
    }
}
ViewController.swift
class ViewController: UIViewController {
   @objc var obj: ObservedObject?
    var observation: NSKeyValueObservation?

    override func viewDidLoad() {
        observation = observe(\.obj!.count, option: [.old, .new]) { object, change in
            print("value=\(change.newValue)")
        }

        obj?.start()
    }

}

参照

Using Key-Value Observing in Swift | Apple Developer Documentation
Swift4のKVOに感動した。 - Qiita
Expressions — The Swift Programming Language (Swift 5.1)

3
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
5