KVO && KVC

Source: Internet
Author: User

KVO:

  • Key-value Observing
    • When the properties of the specified object are modified, the object receives a notification.
    • Simply put, the KVO will automatically notify the appropriate observer when the property of the observed object has been modified each time it is specified.
    • Steps to use:
      • 1. Register, specify the attributes of the person being observed (observers who are actively added by the observer to observe their own)
      • 2. Implementing a callback method
      • 3. Removal of observations
      • Examples of Use:
        • @interface Stockdata:nsobject {
        • NSString * STOCKNAME;
        • float price;
        • }
        • @end
        • @implementation StockData
        • @end

        • -(void) Viewdidload {
        • [Super Viewdidload];

        • STOCKFORKVO = [[StockData alloc] init];
        • [Stockforkvo setvalue:@ "Searph" forkey:@ "StockName"];
        • [Stockforkvo setvalue:@ "10.0" forkey:@ "Price"];
        • To add an observer to the Stockdat object
        • [Stockforkvo addobserver:self forkeypath:@ "Price" options:nskeyvalueobservingoptionnew| Nskeyvalueobservingoptionold Context:null];

        • MyLabel = [[UILabel alloc]initwithframe:cgrectmake (100, 100, 100, 30)];
        • Mylabel.textcolor = [Uicolor Redcolor];
        • MyLabel.Text = [Stockforkvo valueforkey:@ "Price"];
        • [Self.view Addsubview:mylabel];

        • UIButton * b = [UIButton buttonwithtype:uibuttontyperoundedrect];
        • B.frame = CGRectMake (0, 0, 100, 30);
        • [B addtarget:self Action: @selector (Buttonaction) forcontrolevents:uicontroleventtouchupinside];
        • [Self.view addsubview:b];
        • }
        • -(void) Buttonaction {
        • [Stockforkvo setvalue:@ "20.0" forkey:@ "price"];
        • }
        • As a KVO observer needs to implement callbacks
        • -(void) Observevalueforkeypath: (NSString *) KeyPath Ofobject: (ID) object change: (nsdictionary *) Change context: (void *) Context {
        • if ([KeyPath isequaltostring:@ "Price"]) {
        • MyLabel.Text = [Stockforkvo valueforkey:@ "Price"];
        • }
        • }
        • Finally we need to move the viewer
        • -(void) Dealloc {
        • [Stockforkvo removeobserver:self forkeypath:@ "Price"];
        • }

KVC:

  • Abbreviation of keyvaluecoding
    • A mechanism for indirectly accessing an object's properties using a string identifier, rather than being accessed by invoking a setter, getter method.
    • You can read and write member variable values by KVC even if the member variable in the object is not a property
    • How to use:
    • Key methods:
      • Nskeyvaluecodingprotocol
      • Get Value:
        • Valueforkey: The name of the (NSString *) attribute
        • Valueforkeypath: (NSString *) The path of the passed-in property, xx.xx form.
        • Valueforundefinedkey
        • The default implementation is to throw an exception, and you can override this function to do error handling.
      • modifying values
        • Setvalue:forkey:
        • Setvalue:forkeypath:
        • Setvalue:forundefinedkey:
        • Setnilvalueforkey:
        • Called when Nil is set on a non-class object property, and the exception is thrown by default.
      • Case of a one-to-many relationship member
        • Mutablearrayvalueforkey:
        • Ordered one-to-many relationship member Nsarray
        • Mutablesetvalueforkey:
        • Unordered one-to-many relationship member Nsset
        • Demonstration examples:
          • Person class
          • @implementation person
          • @synthesize name,age;//property name will be monitored
          • -(void) changename{
          • [Email protected] "changename directly";
          • }
          • @end
          • The Personmonitor class monitors the Name property
          • @implementation Personmonitor
          • -(void) Observevalueforkeypath: (NSString *) KeyPath Ofobject: (ID) object change: (nsdictionary *) Change context: (void *) Context {
          • if ([KeyPath isequal:@ "name"]) {
          • NSLog (@ "Change happen, old:%@ new:%@", [Change Objectforkey:nskeyvaluechangeoldkey],[change Objectforkey: Nskeyvaluechangenewkey]);
          • }
          • }
          • @end
          • Test code
          • Initializing monitored objects
          • Person *p =[[person alloc] init];
          • Monitoring objects
          • Personmonitor *pm= [[Personmonitor alloc]init];
          • KVO
          • [P addobserver:pm forkeypath:@ "name" Options: (Nskeyvalueobservingoptionnew | Nskeyvalueobservingoptionold) Context:nil];
          • Pre-test data
          • NSLog (@ "P.name is%@", p.name);
          • KVC
          • By means of SetValue, the monitoring of personmonitor will be called
          • [P setvalue:@ "name KVC" forkey:@ "name"];
          • View the value after setting
          • NSLog (@ "p name Get by KVC is%@", [P valueforkey:@ "name"]);
          • The effect is consistent through SetValue
          • [Email protected] "name change by. Name=";
          • Change name by person's own function
          • [P changename];
          • /*
          • Result output
          • 2011-07-03 16:35:57.406 cocoa[13970:903] P.name is name
          • 2011-07-03 16:35:57.418 cocoa[13970:903] change happen, Old:name New:name KVC
          • 2011-07-03 16:35:57.420 cocoa[13970:903] p name Get by KVC is name KVC
          • 2011-07-03 16:35:57.421 cocoa[13970:903] change happen, Old:name KVC new:name change by. name=
          • The last modification is a direct modification, so no notification is generated.
          • */

KVO && KVC

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.