본문 바로가기

iOS

KVO - key-value-observing

728x90
반응형
SMALL

 

원티드 프리온보딩 챌린지에 참여 하면서, 순살 치킨이 되어버렸습니다

정말 정말 정말.. 스스로가 보잘 것 없이 느껴졌습니다. 포켓몬고에서 포켓몬만 2만 마리 넘게 잡은 지난 3달을 지금와서 후회하고 있습니다.

(그래도 오랜만에 하는 UIKit이 너무 반가웠기도 합니다.ㅠㅠㅠ.)

 

우선 나오는 키워드 조차 처음 듣는 게 너무나 많아서, 본인의 부족함을 절실히 느꼈기 때문에.

하나하나 공부해 보겠습니다. ㅠㅠㅠ KVO, Serial Queue Concurrent Queue

https://developer.apple.com/documentation/swift/using-key-value-observing-in-swift

 

Using Key-Value Observing in Swift | Apple Developer Documentation

Notify objects about changes to the properties of other objects.

developer.apple.com

Notify objects about changes to the properties of other objects.

흠.. 객체에게 다른 객체의 속성이 바뀌는 걸 알려주는 거랍니다.

Key-value observing is a Cocoa programming pattern you use to notify objects about changes to properties of other objects. It’s useful for communicating changes between logically separated parts of your app—such as between models and views. You can only use key-value observing with classes that inherit from NSObject.

 

KVO는 코코아 프로그래밍 패턴이고, 너가 다른객체의 속성이 바뀔 때 알려줄 때 사용함.

분할 된 모델, 뷰 사이 변한 값을 사항을 절달하기 유용함. 오직 NSObject에서 상속되는 클래스에서만 KVO 사용가능함.

 

In the example below, the \.objectToObserve.myDate key path refers to the myDate property of MyObjectToObserve:

 

MyObjectToObserve의 myDate 속성을 참조하는 예제임

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!)")
        }
    }
}

You use the oldValue and newValue properties of the NSKeyValueObservedChange instance to see what’s changed about the property you’re observing.

 NSKeyValueObservedChange 인스턴스의 oldValue, newValue 속성들을 사용해서 관찰 중인 속성이 바뀐 걸 확인할 수 있음.


If you don’t need to know how a property has changed, omit the options parameter.

만약에 속성이 어떻게 변경되었는지 알 필요가 없으면 옵션 파라미터를 생략.

 

Omitting the options parameter forgoes storing the new and old property values, which causes the oldValue and newValue properties to be nil.

옵션 파라미터를 생략하면 새 속성과 옛 속성이 저장되지 않음, 때문에 oldValue 및 newValue 속성이 nil이 됨.

 

Associate the Observer with the Property to Observe
옵저버와 속성 연결.

 

You associate the property you want to observe with its observer by passing the object to the initializer of the observer: observer:

객체를 observer의 이니셜라이져에게 넘겨 줌으로써, 관찰할 속성과 observer 연결함.

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

Respond to a Property Change

프로퍼티 변경에 대응

 

Objects that are set up to use key-value observing—such as observed above—notify their observers about property changes. The example below changes the myDate property by calling the updateDate method. That method call automatically triggers the observer’s change handler:

 

key-value observing을 사용하기 위해 설정된 객체들 ,

옵저버에게 프로퍼티 변경에 대해 알려줌.

아래 예시는 updateDate 메서드를 호출해서 myDate 속성을 바꿈.

이 메소드는  observers의 change handler를 불러서 자동으로 트리거함.

(?? 무슨 말인지 도저히 모르겠습니다...지인들에게 물어보고 언젠가 더 공부하는 걸로...)

 

observed.updateDate() // Triggers the observer's change handler.
// Prints "myDate changed from: 1970-01-01 00:00:00 +0000, updated to: 2038-01-19 03:14:08 +0000"

The example above responds to the property change by printing both the new and old values of the date.

위의 예제는 날짜의 새 값과 이전 값을 모두 printing해서,  프로퍼티 변경에 대응함.

728x90
반응형
LIST