I feel that i don't fully understand difference between KVO and NSNotification... They seem to be so similar... Could you make some example showing when is best to use one method and when the other ?
I don't speak about Bind and IB, but i mean add Observer programmatically in my code with NSNotificationCenter or KVO
[self.preferenceController addObserver:self
forKeyPath:@"color"
options:NSKeyValueObservingOptionOld
context:@"Color-change"
];
KVO, which stands for Key-Value Observing, is one of the techniques for observing the program state changes available in Objective-C and Swift. The concept is simple: when we have an object with some instance variables, KVO allows other objects to establish surveillance on changes for any of those instance variables.
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 .
One obvious difference is that delegation is for sending a one-to-one message (to which the receiver can return a value) whereas notification is a one-to-many message (where the receivers cannot return anything to the sender).
KVO and KVC or Key-Value Observing and Key-Value Coding are mechanisms originally built and provided by Objective-C that allows us to locate and interact with the underlying properties of a class that inherits NSObject at runtime.
KVO only works on values, NSNotification can be used for value changes but it can be used for anything and can carry a much greater payload.
For example, you could have an NSNotification posted whenever a file has finished downloading and the userInfo could contain the length of time it took, the number of bytes downloaded and the filesystem path that the file has been saved to.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With