-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Swift에서 키 경로(Key Path)란 무엇이며, 어떻게 사용하나요? #26
Labels
Comments
런타임에 키 경로를 사용하여 속성에 접근하는 방법과 KVO ( Key-Value Observing )
KVC ( Key-Value-Coding )
KVO ( Key-Value Observing )
사용예시import Foundation
// class 사용, NSObject 상속
class Person: NSObject {
// @objc Attribute 사용 + dynamic Modifire 사용
@objc dynamic var name: String
init(name: String) {
self.name = name
}
}
var person = Person(name: "Phang")
// Observer
// old, new - 변경 전, 변경 후
var person1 = Person(name: "Phang")
person1.observe(\.name, options: [.old, .new]) { (object, change) in
print("Name changed from \(change.oldValue) to \(change.newValue)")
}
person1.name = "팽" // Name changed from Optional("Phang") to Optional("팽")
// initial - Observer 등록 전
var person2 = Person(name: "Kim")
person2.observe(\.name, options: [.old, .new, .initial]) { (object, change) in
print("Name changed from \(change.oldValue) to \(change.newValue)")
}
// Name changed from nil to Optional("Kim")
// prior - 변경 전, 후
var person3 = Person(name: "Hwang")
person3.observe(\.name, options: [.old, .new, .prior]) { (object, change) in
print("Name changed from \(change.oldValue) to \(change.newValue)")
}
person3.name = "Choi"
// Name changed from Optional("Hwang") to nil
// Name changed from Optional("Hwang") to Optional("Choi")
KVO 는 분리된 파트간의 변경사항을 전달할 수 있고, 내부 소스 변경 없이 상태변화에 대응하고, 변경 전후의 값을 알 수 있는 장점이 있지만, NSObject 를 상속받아야하고, dealloc 시 옵저버를 지워줘야 하는 불편함이 있다. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Swift에서 키 경로(Key Path)란 무엇이며, 어떻게 사용하나요?
The text was updated successfully, but these errors were encountered: