Answer the question
In order to leave comments, you need to log in
What is the difference between Key-Value Observing and Notifications?
What is the difference between Key-Value Observing and Notifications? When to use what?
Answer the question
In order to leave comments, you need to log in
KVO - allows objects to subscribe to changes to specific object properties. In swift 4 it looks like this
class MyObjectToObserve: NSObject {
@objc dynamic var myDate = NSDate()
func updateDate() {
myDate = NSDate()
}
}
class MyObserver: NSObject {
@objc var objectToObserve: MyObjectToObserve
var observation: NSKeyValueObservation?
init(object: MyObjectToObserve) {
objectToObserve = object
super.init()
observation = observe(\.objectToObserve.myDate) { object, change in
print("Observed a change to \(object.objectToObserve).myDate, updated to: \(object.objectToObserve.myDate)")
}
}
}
let observed = MyObjectToObserve()
let observer = MyObserver(object: observed)
observed.updateDate()
NotificationCenter
. Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question