it provides a mechanism for listeners to receive notifications when the properties of the specified object have been modified.
It's like we set an alarm clock for the phone, and when the time is set, the alarm goes off, and we know it's time.
in this process, we are listeners, the alarm clock is the object to be monitored
we create a student class that uses the KVO pattern to add listeners to the Username property in it (the viewer xsstudent*su = [[xsstudentalloc]init]; su.name= @ "Zhangsan";
Su. Age = 12;
//observer who is the observer?
//keypatha listener's properties, such as listening to a student'snameProperties
//options:What you listen to nskeyvalueobservingoptionnew,nskeyvalueobservingoptionold These two parameters mean listening to its new and old values
[Su Addobserver: SelfForkeypath:@ "Name"Options:nskeyvalueobservingoptionnew|
NskeyvalueobservingoptionoldContext:Nil];
// Modify Properties, Trigger method su. name = @ "Lis" ;
//The Observer observes the method that occurs when a value changes
- (void) Observevalueforkeypath: (NSString*) KeyPath ofobject: (ID) Object change: (nsdictionary*) Change context: (void*) Context
{
//change in the dictionaryOld New is a keyword that is specifically used to store new valuesand theOld value
NSLog(@ "Oldname%@", [ changeObjectforkey:@ "old"]); NSLog(@ "New%@", [Change objectforkey:@ "new"]);}
Note that here (nsstring*) KeyPath is the key you created when you added the observer, and if you want to listen to multiple properties, You can determine exactly which value changes are triggering the method based on the entire value .
iOS design mode KVO key-value observing key-value observer mode simple and practical and introduction