KVO Key-Value Observing Key-Value observer mode in iOS Design Mode
It provides a mechanism for the listener to receive notifications when the attributes of the specified object are modified.
It's like we set an alarm clock for our cell phone. When the time is up, the alarm will sound and we will know the time is up.
In this process, we are the listener, and the alarm clock is the Monitored object.
We create a student class and use the KVO mode to add listeners to the username attribute (Observer XSStudent * su = [[XSStudentalloc] init]; su. name = @ "zhangsan ";
Su. age = 12;
// Who is the Observer?
// Attributes of the KeyPath listener, such as the name attribute of the listener student
// Options: content of the listener // NSKeyValueObservingOptionNew, NSKeyValueObservingOptionOld two parameters mean to listen to its new value and old value
[Su addObserver: self forKeyPath: @ "name" options: NSKeyValueObservingOptionNew |
NSKeyValueObservingOptionOld context: nil];
// Modify attributes. Trigger method su. name = @ "lis ";
// The method observed by the observer when the value changes
-(Void) observeValueForKeyPath :( NSString *) keyPath ofObject :( id) object change :( NSDictionary *) change context :( void *) context
{
// The old new in the change dictionary is a keyword used to store new and old values.
NSLog (@ "oldname % @", [changeobjectForKey: @ "old"]); NSLog (@ "new % @", [change objectForKey: @ "new"]);}
Note: Here (NSString *) The keyPath is the key you created when you added the observer. If you want to listen to multiple attributes, you can determine which value changes trigger this method based on the entire value.