About KVC \ KVO in objective-C

Source: Internet
Author: User

Anyone familiar with OC syntax may understand this: In oC, the member variables or methods of classes are not absolutely private.

Private methods cannot be accessed directly through class instances, but they can be accessed through the OC's "compile RunTime" mechanism, that is, the "Blind Man" mechanism (I personally understand: as long as the class has method, if you are a private owner, I can call you by using the javasmselector function.) Speaking of this, some students may naturally remember how to access private variables? It seems that we have never done this before. However, the reality is that we can, but generally, after setting variables as private variables of the class, we do not want ourselves or others to access them, otherwise, I can only say that you are looking for a bid again ..............

Well, let's get down to the point. This article mainly aims to introduce the implementation mechanisms of KVC, KVO, and KVB in OC. Of course, it must be related to those mentioned above.

1. KVC: Key-value coding)

It is a mechanism that uses string identifiers to indirectly Access Object Attributes. It is the basis of many technologies. The main method is two pairs of Methods: (setvalue: forkey, valueforkey), setvalue: forkeypath, valueforkeypath); what is the role of this thing? I will not talk about the principle first, but how to use it first, example:

@ Interface a {nsstring * Foo ;}
... // Other code
@ End
@ Interface B {nsstring * bar; A * Mya ;}
... // Other code
@ End
@ Implementation B
... // Assume that objects a and B of type A are
B A * A = ...;
B * B = ...;
Nsstring * S1 = [A valueforkey: @ "foo"]; // correct
Nsstring * S2 = [B valueforkey: @ "bar"]; // correct
Nsstring * S3 = [B valueforkey: @ "Mya"]; // correct
Nsstring * S4 = [B valueforkeypath: @ "Mya. foo"]; // correct
Nsstring * S5 = [B valueforkey: @ "Mya. foo"]; // Error
Nsstring * S6 = [B valueforkeypath: @ "bar"]; // correct
...
@ End

In fact, the two pairs of methods mentioned above are basically the same, but the value of valueforkeypath is a path (the path is a dot between the paths. for example, if the data member is the object itself, the value search process goes down.
Note that the names of Data Members here are strings. The best use of this method is to bind data (names) to some triggers (especially method calls,
For example, key-value observing (KVO.

The code above demonstrates that the member variables of the class can also be accessed using the two methods of the base class nsobject, not necessarily directly through the class instance, but this method still has certain risks, please refer to this: http://www.devbean.info/2011/04/from_cpp_to_objc_20/ for specific dangerous situations
Then let me talk about the principle. I copied it. Let's take a look at it:
KVC uses an ISA-swizzling technology. Isa-swizzling is a type-based hybrid pointer mechanism. KVC mainly uses Isa-swizzling to implement internal search and positioning.
The ISA pointer, as its name implies (that is, a kind of), points to the class of the object that maintains the sub-table. The sub-Table actually contains pointers to methods in the implementation class, and other data.

For example, the following line of KVC code:

[Site setvalue: @ "sitename" forkey: @ "name"];
It will be processed by the compiler as follows:

Sel sel = sel_get_uid ("setvalue: forkey :");
IMP method = objc_msg_lookup (site-> Isa, Sel );
Method (site, Sel, @ "sitename", @ "name ");
First, we will introduce two basic concepts:

(1) SEL data type: it is the environment parameter for the compiler to run the methods in objective-C.

(2) imp data type: it is actually a function pointer within the compiler. When the objective-C compiler processes and implements a method, it points to an imp object, which is a type expressed in C Language (in fact, when the objective-C compiler processes it, C language ).
The implementation of KVC is clear: when an object calls setvalue,
(1) first, find the required environmental parameters for running the method based on the method name.
(2) he will use his ISA pointer to combine environment parameters to find the specific method to implement the interface.
(3) directly find the specific method implementation.

2. KVO: Key-value observing (key-value listening) and KVB: Key-value binding (key-value binding)

These two mechanisms are used in combination,

Key-value observing (KVO): This mechanism allows an object to receive notifications when the attributes of the specified object are modified. Each time the attribute of the object to be observed is modified, KVO automatically notifies the corresponding observer.

Advantages of KVO

When attributes change, KVO will provide automatic message notifications. This architecture has many advantages. First, developers do not need to implement this solution by themselves: A Message notification is sent every time the attribute changes. This is the biggest advantage of the KVO mechanism. This solution has been clearly defined and can be easily used with framework-level support. Developers do not need to add any code or design their own observer models, which can be used directly in the project. Secondly, the KVO architecture is very powerful, and it can easily support multiple observers to observe the same attribute and related values.

Two basic methods of KVB implementation
1: add the observer addobserver: forkeypath: Options: context:
2: The processing function observevalueforkeypath: ofobject: Change: context:

The most obvious use cases of KVO and KVB are the real-time display of strong lines on some interfaces, such as stock trend and ticket balance. This method saves us the trouble of notifying users by ourselves, with this in mind, I found that the progress of the download page in the initial fund and 91 market can also be displayed in this way.

Let's talk about it first. It's even more exciting to be continued ........

Original English link: http://maniacdev.com/2012/12/helper-classes-for-easy-cocoa-touch-key-value-observing-kvo-and-key-value-binding-kvb/

 

 

1. setvalue: forkey: You can access setxxx: method.

2. valueforkey: You can access instance variables and methods without parameters.

3. performselector can access all methods.

 

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.