Kvc kvo kvb for IOS development (39)

Source: Internet
Author: User

KVC (Key Value Coding)

KVO (Key Value Observing)

KVB (Key Value Binding)

KVO is an important mechanism of Cocoa. It provides methods to observe the changes of a certain attribute and greatly simplifies the code. This observation-the observed model applies to such situations. For example, A property in B (view class) changes according to A property value change in A (data class. For cocoa, which advocates MVC, kvo is widely used. (This mechanism sounds like Notification, but notification requires an object that sends notification, usually icationcenter center, to notify the observer. Kvo directly notifies the observed object .)

When use KVO, it usually follows below:

1 Registration:

-(Void) addObserver :( NSObject *) anObserver forKeyPath :( NSString *) keyPath options :( NSKeyValueObservingOptions) options context :( void *) context
KeyPath is the attribute value to be observed. options shows you the selection of key value changes, while context facilitates the transmission of the data you need (note that this is a void type)

2. Implementation and change methods:

-(Void) observeValueForKeyPath :( NSString *) keyPath ofObject :( id) object
Change :( NSDictionary *) change context :( void *) context
Change stores some changed data, such as the data before the change and the data after the change. If the context is not empty during registration, the context can be received here.

Is it easy? The kvo logic is very clear and the implementation steps are simple.

If you have said so much, everyone is eager to try it. However, before that, we still need to understand the KVC mechanism. Actually, knowing the logic of kvo is just to help you understand it. What you need to really master is not what kvo implementation steps are, but KVC, because KVO can be used only for objects that comply with the KVC standard (KVO is strongly recommended to be understood first ).

KVC is a mechanism for indirect access to object attributes (characterized by strings), rather than directly calling the accessor method of an object or directly accessing a member object.

A key is a string used to determine a value of an object. It is usually the same as the accessor method or variable and must begin with a lowercase letter.

Key path is the key separated by ".". property can be object whick also contains property. For example, we can have keys like person or key path like key. gender.

(SetValue: forKey, valueForKey :), (setValue: forKeyPath, valueForKeyPath :)


When obtaining the property value, you can use the valueForKey: method to set the property value to setValue: forKey :. At the same time, KVC defines valueForUndefinedKey for undefinedkey: For undefined attribute values, you can reload it to obtain the implementation you want (In addition, KVC defines the informal protocol that carries NSKeyValueCoding ).

Property is introduced in O-C 2.0, and we can also access the property through the. Operator. The following is an example:

@ Property NSInteger number;

Instance. number = 3;
[Instance setValue: [NSNumber numberWithInteger: 3] forKey: @ "number"];
Note that values in KVC must be objects.

The preceding section describes how to use KVC to obtain and set attributes. Next, we need to describe the KVC accesser method ). Apple generally provides the following conventions:

-Key:, and setKey: (the name convention used is the same as that used by setter/getter ). You can use setNilValueForKey: For undefined attributes :.

Now, you have mastered the basic concepts of KVC. The reason is basic, because it only involves single-value situations, kvc can also use many-to-many relationships, so we will not talk about it here, leaving you with the space to learn.

Next, we will take the collection as an example to practice the KVC.

In ios, array is often used as the data source of tableview:

Suppose we already have N data records. After an operation, we have two more records after the original data, or we can update and replace some data in N. Without KVC, we can use the reloadData method or reloadRowsAtIndexPaths. The disadvantage of the previous one is that N is greatly consumed. Imagine that you have added only a few pieces of data but need to reload the previous N pieces of data. The disadvantage of the latter method is that the Code is redundant. You need to calculate each indexPath at a time and reload it again. In addition, you need to know in advance what situations will cause data updates,

If KVC/kvo is used, this will solve the problem. You don't have to worry about the number of data records appended or updated.

The following describes how to add data:

Implement insertObject: inKeyAtIndex: Or insertKey: atIndexes. At the same time, in kvo, we can use the change dictionary to find out what kind of change has taken place and handle it accordingly.

Add an example: Click to download

 

1. Person class
@ Implementation Person @ synthesize name, age; // The attribute name will be monitored.
-(Void) changeName {name = @ "changeName directly" ;}@ end 2. the PersonMonitor class monitors the name attribute @ 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 3 test code // initialize the Monitored object Person * p = [[Person alloc] init]; // monitoring object PersonMonitor * pm = [[PersonMonitor alloc] init]; [p addObserver: pm forKeyPath: @ "name" options :( NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld) context: nil]; // NSLog (@ "p. name is % @ ", p. name); // using the setvalue method, the monitoring of PersonMonitor will be called [p setValue: @ "name kvc" forKey: @ "name"]; // view the set value NSLog (@ "p name get by kvc is % @", [p valueForKey: @ "name"]); // The effect is consistent with that of p. name = @ "name change. name = "; // change name [p changeName] by using the person function; the result is output 16:35:57. 406 Cocoa [13970: 903] p. name is name 16:35:57. 418 Cocoa [13970: 903] change happen, old: name new: name kvc 16:35:57. 420 Cocoa [13970: 903] p name get by kvc is name kvc 16:35:57. 421 Cocoa [13970: 903] change happen, old: name kvc new: name change. name = the last modification was a direct modification, so there was no way to generate a notification KVB
Two basic methods

1: add the Observer to the object

AddObsever: forKeyPath: options: context;

2: processing function for the Observer to receive information

ObseveValueForKeyPath: ofObject: change: context;

 

 

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.