KVO

KVO (Key-Value Observing) 소개

(MVC 에서 모델 Model 의 변화를 뷰 View 에 반영하기 위함 등)

예제 (Swift 3.x)

class TestClass: NSObject {
  private var context: UInt8 = 0
  lazy var someView: UIView = {
    return UIView(frame: CGRect(x: 20, y: 20, width: 50, height: 50))
  }()
  
  override init() {
    super.init()
    
    someView.addObserver(self, forKeyPath: "frame", options: [.new, .old], context: &context)
  }
  
  override func observeValue(forKeyPath keyPath: String?, 
                             of object: Any?, 
                             change: [NSKeyValueChangeKey : Any]?, 
                             context: UnsafeMutableRawPointer?) {
    if let keyPath = keyPath {
      print("\\(keyPath) updated")
    }
  }
}

예제 (Swift 4.x)

Swift 4 에서 KVO ​사용해보기

class SomeClass: NSObject {
  @objc dynamic var value: String = ""
}

let someObject = SomeClass()

someObject.observe(\\.value) { (object, change) in
  print("SomeClass object value changed to \\(object.value)")
}

someObject.value = "test"  // TEST