Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSNotification VS KVO

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"
];
like image 698
MatterGoal Avatar asked Jul 15 '11 13:07

MatterGoal


People also ask

When to use KVO?

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.

When to use KVO in Swift?

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 .

What is the difference between delegate and notifications?

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

What is KVC and KVO in Swift?

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.


1 Answers

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.

like image 112
iain Avatar answered Sep 24 '22 14:09

iain