The underlying implementation of KVC

Source: Internet
Author: User

Objective-c inside the Key-value observing (KVO) mechanism, very good, can be very good to reduce the watering code. About KVO study, you can refer to the article: "Key-value observing Quick Start": http://www.cocoadev.cn/Objective-C/Key-Value-Observing-Quick-Start-cn.asp

KVO Concept:

KVO is a core concept in cocoa, which is simple to understand that objects that focus on model data (Key) can be registered as listeners, and once the value of the model Key changes, it is broadcast to all listeners

KVO mechanism:

KVO (Key value Observe) is the Protocol (nskeyvaluecoding) used to set values or values in cocoa, which is a bit similar to Java EJBS, and is designed to make it easy to set class member values by standardizing variables and function names. It's a bit like notification, but it provides a way to see how a property changes, and notification needs an object to send notification, so KVO simplifies the code significantly more than notification.

This observation-the observed model is suitable for situations where, for example, a change in a property value of a (data Class) makes a corresponding change in a property in B (view Class). For the cocoa of MVC, KVO application is of high value.

Key-value Coding (KVC) Implementation analysis

KVC used a isa-swizzling technique. Isa-swizzling is the type-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 the is a kind of), points to the class that maintains the sub-published object. This sub-publication actually contains pointers to the methods in the implementation class, and other data.

For example, the following line KVC code:

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

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

First, we introduce two basic concepts:

(1) SEL data type: It is the environment parameter of the method that the compiler runs in Objective-c.

(2) IMP data type: He's actually a function pointer to the compiler's internal implementation. When the Objective-c compiler handles the implementation of a method, it points to a Imp object, which is the type of the C language expression.

For information on how to find a pointer to an implementation function, refer to the article: "How to avoid dynamic binding and get method Address" Objective-c: http://www.cocoadev.cn/Objective-C/Get-method-address.asp

The implementation of this KVC is clearly clear: when an object calls SetValue, (1) first finds the environment parameters required to run the method according to the method name. (2) He will combine the environment parameters from his own Isa pointer to find the specific method implemented by the interface. (3) The specific method can be directly found.

Key-value Observing (KVO) implementation

The KVC mechanism described above adds KVO's automatic observation notification mechanism to the system.

When the observer registers the attributes of an object, the ISA pointer points to an intermediate class instead of the real class when the object's ISA pointer is modified. So the ISA pointer does not actually need to point to the real class of the instance object. So our program is best not to rely on the ISA pointer. When invoking a method of a class, it is best to clarify the class name of the object instance.

Friends familiar with Kvo know that KVO will only work if we call KVC to access the key value. So it is certain that the KVO is based on the KVC implementation. In fact, after looking at our analysis above, the concept of the relationship KVO architecture will be the same.

Because of the implementation mechanism of KVC, it is easy to see the key of a KVC operation, and then it is easy to match the key in the Observer registry. If the key being accessed is the observed key, then we can easily find the observer object in the Observer registry and send him a message inside.

=======================================================

A brief introduction to KVO/KVC is available as an introductory reading.

Please correct me if some terms are not accurate enough.

Welcome to the discussion.

KVO is an important mechanism for cocoa, which provides a way to observe a change in a property, greatly simplifying the code. This observation-the observed model is suitable for situations where, for example, a change in a property value of a (data Class) makes a corresponding change in a property in B (view Class). For MVC-Cocoa, the KVO application is very extensive.

When KVO is applied, the following processes are usually followed:

1 Registration:

-(void) Addobserver: (NSObject *) anobserver Forkeypath: (NSString *) keypath options: (nskeyvalueobservingoptions) Options context: (void*) context

KeyPath is the attribute value to observe, Options gives you the option of observing the change of the key value, and the context facilitates the transfer of the data you need (note that this is a void type)

2 Implementing the Change method:

-(void) Observevalueforkeypath: (NSString *) KeyPath Ofobject: (ID) object change: (nsdictionary *) Change context: (void*) Context

Changes are stored in change data, such as pre-change data, changed data, and if the context is not empty at the time of registration, the context can be received here.

Isn't it simple? The logic of KVO is very clear and the steps are simple to implement.

With so much to say, everyone has to be tempted. Before we do, however, we need to understand the KVC mechanism. In fact, know that the logic of KVO is only to help you understand, to really grasp, is not what the KVO implementation steps, but lies in KVC, because only the KVC standards of the object to use KVO (strongly recommended to use KVO first understand KVC).

KVC is a mechanism for indirectly accessing object properties (represented by strings), rather than directly invoking the object's accessor method or accessing the member object directly.

A key is a string that determines the value of an object, usually with the same name as the accessor method or variable, and must start with a lowercase letter. KeyPath is to "." Separated key, because the property value can also contain attributes. For example, we can be a person such a key, you can also have key.gender such a key path.

When you get the property value, you can set the property value by using the Valueforkey: Method, Setvalue:forkey:. At the same time, KVC defines valueforundefinedkey for undefined attribute values: You can overload to get the implementation you want (supplemented by the KVC definition in the informal protocol that contains nskeyvaluecoding).

The property is introduced in O-c 2.0, and we can access it through the. operator. Here's a straight look at the example:

@property Nsinteger number;

Instance.number = 3;

[Instance Setvalue:[nsnumber Numberwithinteger:3] forkey:@ "number"];

Note that value in KVC must be an object.

The above describes the use of KVC to get/set properties, the next step is to illustrate the implementation of KVC accessor methods (accessor method). Apple's usual practice is to:

-key:, as well as Setkey: (used name Convention and Setter/getter name consistent). You can use Setnilvalueforkey for undefined attributes:.

At this point, you should have mastered the basic concepts of KVC. The reason is basic, because only the single value of the situation, KVC can also be applied to the multi-relationship, here does not say, leaving you the space for self-study

Next, we will take the set as an example, to the grasp of the KVC to carry out a bit of practice.

An array is selected because, in iOS, an array is often made as a tableview data source, in which case:

Suppose we already have n data, after an operation, there are 2 more records after the original data, or some data in n is updated and replaced. We can use the Reloaddata method or the reloadrowsatindexpaths without using KVC. The disadvantage of the former is that if N is very large, it consumes very much. Imagine that you have added only a few data but you want to reload the previous n data. The disadvantage of the latter method is that the code will be very redundant, you have to calculate each indexpath and then go to reload, but also in advance to think about exactly under what circumstances will cause data updates,

If you use KVC/KVO, the hassle will be solved, and you won't have to worry about appending or updating how many data.

The following is an example of adding data to illustrate the methods that need to be implemented:

Implement Insertobject:inkeyatindex: or Insertkey:atindexes. At the same time in the kvo we can know what changes have occurred through the change of the dictionary, so as to deal with them accordingly.

Http://www.cocoadev.cn/Objective-C/Key-Value-Observing-Quick-Start-cn.asp

The difference between KVO and notification:

Notification is the need for a send notification object, usually Notificationcenter, to notify the Observer.

KVO is the direct notification to the observer, and the logic is very clear, the implementation of simple steps.

The underlying implementation of 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.