Some understanding of KVO and KVC in iOS

Source: Internet
Author: User

Key-value Observing (abbreviated KVO): Allows the object to receive notification mechanisms when the properties of the specified object have been modified. Each time a specified object's properties are modified, KVO automatically notifies the corresponding observer, equivalent to the observer pattern in the design pattern.

Advantages of KVO:
When a property changes, KVO provides an automatic message notification. There are many benefits to this architecture. First, developers do not need to implement this scenario themselves: send a message notification every time a property changes. This is the biggest advantage that the KVO mechanism offers. Because this program has been clearly defined, access to framework-level support can be easily adopted. Developers do not need to add any code, they do not need to design their own observer model, can be used directly in the project. Second, the KVO architecture is very powerful, and it is easy to support multiple observers to observe the same attribute and related values.

Here we write a simple demo, how to use the KVO

First define a class, declare two attributes, name and PID;

@interface datamodel:nsobject
{


    
    
    nsstring *name;
    NSString *pid;
    


}
In the controller.

-(void) viewdidload {[Super viewdidload];
    
    
    Dm=[[datamodel alloc] init];
    [DM setvalue:@ "Daren" forkey:@ "name"];
    
    [DM setvalue:@ "1" forkey:@ "pid"]; Registering as an observer option parameter specifies the information that is provided to the observer when the change notification is sent. You can use the Nskeyvalueobservingoptionold option to provide an initial object value to the observer in the form of an item in the Change dictionary.
    Specify the nskeyvalueobservingoptionnew option to add a new value as an item to the change dictionary. [DM addobserver:self forkeypath:@ ' name ' options:nskeyvalueobservingoptionnew|
    
    Nskeyvalueobservingoptionold Context:nil];
    Testlabel=[[uilabel alloc] init];
    [TestLabel Setframe:cgrectmake (20, 20, 100, 30)];
    [TestLabel Setbackgroundcolor:[uicolor Clearcolor]];
    
    [TestLabel Settintcolor:[uicolor Blackcolor]];
    
    [TestLabel settext:[dm valueforkey:@ "name"]];
    
    
    
    [Self.view Addsubview:testlabel];
    
    UIButton *testbutton=[uibutton Buttonwithtype:uibuttontyperoundedrect];
    
    [Testbutton Setframe:cgrectmake (20, 100, 100, 70)];
    [Testbutton settitle:@ "test" forstate:uicontrolstatenormal]; [TeStbutton addtarget:self Action: @selector (testpressed:) forcontrolevents:uicontroleventtouchupinside];
    
    
    

    
[Self.view Addsubview:testbutton];
    
    


}-(void) testpressed: (ID) Sender {[DM setvalue:@ ' Wangzi ' forkey:@ ' name ']; }-(void) Observevalueforkeypath: (NSString *) KeyPath Ofobject: (ID) object change: (nsdictionary *) Change context: (void * context {if ([keypath isequaltostring:@ "name"]) {Testlabel.text = (NSString *) [DM valueforkey:@ ' name '
    ];
    
    }-(void) Dealloc {[TestLabel release];
    
    [DM removeobserver:self forkeypath:@ "name"];

    
    [DM release];
    
[Super Dealloc];
 }
In the above code, we set the text of the label to change with the value of a key in the Datamodel class, which is a simple application of KVO. But KVO is based on KVC, what is KVC.

Kvc:key-value coding, literal translation is: The key value code. In short, it is to set the value of the attribute; In complex terms, according to the internet, KVC used a isa-swizzling technique. Isa-swizzling is the type of mixed pointer mechanism. KVC mainly through the isa-swizzling, to achieve its internal search and positioning. The ISA pointer, as its name implies, (that is, the meaning of is a kind of), points to the class of the object that maintains the split publication. The publication actually contains pointers to methods in the implementation class, and other data.

For example, the first line of the following KVC code, in fact, is equivalent to the normal code in the second line:

[MyClass setvalue:@ "Daren" forkey:@ "name"];

Myclass._name = @ "Daren";


The KVC code is processed by the compiler:

Sel sel = Sel_get_uid ("Setvalue:forkey:");
IMP method = Objc_msg_lookup (Myclass->isa,sel);
Method (site, SEL, @ "Daren", @ "name");


The inner implementation of the KVC is clearly clear: an object when the SetValue is invoked:

A. First find the environment parameters needed to run the method based on the method name.

B. It will combine the environment parameters from its own ISA pointer, and find the interface of the concrete method implementation.

C. Further direct lookup of the specific methods to achieve.


The difference between the notification and the KVO is that it is a direct interaction between objects, and notification needs notificationcenter as an intermediate interaction. These are some of the more shallow understanding, a deeper principle, but also need everyone to supplement ~ ~ ~ ~

Related Article

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.