iOS design mode KVO key-value observing key-value observer mode simple and practical and introduction

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.