LoginSignup
12
11

More than 5 years have passed since last update.

Swiftでプロパティ監視(KVO)

Last updated at Posted at 2015-11-28

プロパティを監視して、変更があった場合にイベントを受け取る仕組みがSwiftにはあって、Key Value Observing(KVO)と呼ぶらしい。

監視対象に自身を登録

hoge.addObserver(self, forKeyPath: "name", options: .New, context: nil)

プロパティ変更ハンドラ

override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
    // ここで処理を行う
}

監視を削除

hoge.removeObserver(self, forKeyPath: "name")

jsなどのaddEventListenerと使い方は似ています

12
11
2

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
12
11