본문 바로가기
#모바일 [Mobile]/iOS

[iOS] KVO (Key-Value Observing)

by cy_mos 2022. 1. 24.
반응형
카테고리 게시글 작성 날짜 게시글 최근 수정 날짜 작성자
iOS 2022.01.24. 11:09 2022.01.24. 11:09 Dev.Yang

 

🛠 Key-Value Observing

객체 프로퍼티의 변경에 관하여 다른 객체에게 알림을 주는 코코아 프로그래밍 패턴입니다.

(Notify objects about changes to the properties of other objects)
 
 
  • NSObject를 상속하는 Class만이 사용이 가능합니다.
  • 프로퍼티 (Property)에 대한 변경 알림을 등록하고자 하는 경우에는 @objc dynamic 키워드를 지정하여야 합니다.
  • NSObject 상속하기에 Objective-C Runtime 의존적이라는 단점을 가지고 있습니다.
  • 두 객체 간의 동기화 작업에 유용하게 사용이 되며 다른 객체의 내부 상태 변환을 알기 위하여 추가적인 구현 또는 변경이 필요하지 않는 장점을 가지고 있습니다.

 

🧩 NSKeyValueObservingOptions 관련 옵션

  • static var new: NSKeyValueObservingOptions - 새로운 속성 값을 가져올 수 있는 옵션  (Indicates that the change dictionary should provide the new attribute value, if applicable)
  • static var old: NSKeyValueObservingOptions - 새로운 속성 직전의 값을 가져올 수 있는 옵션 (Indicates that the change dictionary should contain the old attribute value, if applicable)
  • static var initial: NSKeyValueObservingOptions - 생성자를 통하여 초기화 값을 가져올 수 있는 옵션 (If specified, a notification should be sent to the observer immediately, before the observer registration method even returns)
  • static var prior: NSKeyValueObservingOptions - 모든 상태 값을 가져올 수 있는 옵션 (Whether separate notifications should be sent to the observer before and after each change, instead of a single notification after the change)

🛠 Key-Value Observing Example Source Code

class MyObjectToObserve: NSObject {

    @objc dynamic var myDate = NSDate(timeIntervalSince1970: 0) // 1970
    
    func updateDate() {
        myDate = myDate.addingTimeInterval(Double(2 << 30)) // Adds about 68 years.
    }
}

class MyObserver: NSObject {

    @objc var objectToObserve: MyObjectToObserve
    var observation: NSKeyValueObservation?
    
    init(object: MyObjectToObserve) {
        objectToObserve = object
        super.init()
        
        observation = observe(
            \.objectToObserve.myDate,
            options: [.old, .new]
        ) { object, change in
            print("myDate changed from: \(change.oldValue!), updated to: \(change.newValue!)")
        }
    }
}

let observed = MyObjectToObserve()
let observer = MyObserver(object: observed)

🚀 REFERENCE

 

Apple Developer Documentation

 

developer.apple.com

 

Key-Value Observing(KVO) in Swift

안녕하세요 :) Zedd입니다. 오늘은 KVO에 대해서 공부! # KVO - Key-Value Observing의 약자 - 객체의 프로퍼티의 변경사항을 다른 객체에 알리기 위해 사용하는 코코아 프로그래밍 패턴 - Model과 View와 같

zeddios.tistory.com

반응형

댓글