D
D
doublench212017-08-29 09:51:11
iOS
doublench21, 2017-08-29 09:51:11

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

1 answer(s)
A
Alexander Tikhonov, 2017-08-29
@doublench21

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()

Notifications - Defines a one-to-many dependency between objects so that when the state of one object changes, all dependents on it are notified. On iOS, it is represented as NotificationCenter.
Based on the definitions, use what you need.
If, for example, you need to process the user logout in different places, then use Notifications. If you need to track a name change in a profile, then KVO.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question