Simple comparison between KVC and KVO, KVCKVO is simple

Source: Internet
Author: User

Simple comparison between KVC and KVO, KVCKVO is simple

1. Key Value Coding ):

1. In fact, it is often used in actual development: After receiving json data, parse it into NSDictionary, and then create a Model for the field corresponding to the dictionary, define a class method + (instancetype) modelWithDictionary (NSDictionary *) in the Model to call the keyDictionary Method

1 [self setValuesForKeysWithDictionary:jsonObject];

In this way, we can build the dictionary into a Model.

2. Then, you can call the following methods for special processing of some fields that you want to process. For example, if some keys are of the dictionary type, you can do so in the following ways:

1234567891011 -(void) setValue:(id)value forKey:(NSString *)key   if([key isEqualToString:@"products"])       for(NSMutableDictionary *productDict in value)           Prodcut *product = [[Product alloc] initWithDictionary:prodcutDict];       [self.products addObject:product];       }

3. Another case is that the Key is not defined at all. You can rewrite the following method to re-map the key and value to the upper number:

123456789 - (void)setValue:(id)value forUndefinedKey:(NSString *)key     if([key isEqualToString:@"nameXXX"]) = value;     if([key isEqualToString:@"ageXXX"])         self.age = value;     else         [super setValue:value forKey:key]; }



II. Key-Value Observing ):

KVO Overview:
KVO, that is, Key-Value Observing, provides a mechanism. When the attribute of a specified object is modified, the object will receive a notification.
In short, KVO automatically notifies the corresponding observer after the attribute of the specified object to be observed is modified.

Advantages of KVO:
When attributes change, KVO will provide automatic message notifications. In this way, developers do not need to implement the solution by themselves: Send a message Notification 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.

The procedure is as follows:
1. Registration, specifying the properties of the observer,
2. Implement callback Methods
3. Callback Triggering Method
4. Remove observation

The example code of KVO is as follows:
############## Model )###############
# Import <Foundation/Foundation. h>
@ Interface Music: NSObject {
// Listener attributes
NSString * musicName;
@ End

# Import "Music. h"
@ Implementation Music
@ End

############## ViewController )###############
# Import <UIKit/UIKit. h>
@ Class Music;
@ Interface ViewController: UIViewController {
Music * music;
@ Property (nonatomic, retain) Music * music;
@ End

@ Implementation ViewController
@ Synthesize music;

# Pragma mark-View lifecycle

-(Void) viewDidLoad
[Super viewDidLoad];

Music = [[Music alloc] init];

// Add observer registration called when the attribute changes
[Music addObserver: self forKeyPath: @ "musicName" options: NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context: nil];

// UILabel Control
UILabel * musicLabel = [[UILabel alloc] initWithFrame: CGRectMake (20,150,280, 21)];
MusicLabel. font = [UIFont fontWithName: @ "ArialMT" size: 18];
MusicLabel. textColor = [UIColor redColor];
MusicLabel. tag = 100;
[Self. view addSubview: musicLabel];
[MusicLabel release];

// UITextField Control
UITextField * musicTextField = [[UITextField alloc] initWithFrame: CGRectMake (20,200,280, 21)];
MusicTextField. font = [UIFont fontWithName: @ "ArialMT" size: 18];
MusicTextField. placeholder = @ "Please enter some words .";
MusicTextField. backgroundColor = [UIColor whiteColor];

// Called when UITextField inputs the content
[MusicTextField addTarget: self action: @ selector (textFieldDidChange :) forControlEvents: UIControlEventEditingChanged];

[Self. view addSubview: musicTextField];
[MusicTextField release];

Self. view. backgroundColor = [UIColor grayColor];

-(Void) textFieldDidChange :( id) sender {
UITextField * textField = (UITextField *) sender;
NSLog (@ ">>>>>>>>>>>>>>>>%@", textField. text );
// Modify the properties of the listener. The following callback method is called.
[Music setValue: textField. text forKey: @ "musicName"];

// As long as the "musicName" attribute of the Music class changes, the following methods are triggered:
-(Void) observeValueForKeyPath :( NSString *) keyPath ofObject :( id) object change :( NSDictionary *) change context :( void *) context {
UILabel * label = (UILabel *) [self. view viewWithTag: 100];
// If the changed attribute is "musicName"
If ([keyPath isw.tostring: @ "musicName"]) {
// Assign the value of the current musicName attribute to UILabel
Label. text = [music valueForKey: @ "musicName"];
// Output the value before the change
NSLog (@ "old musicName is % @", [change objectForKey: @ "old"]);
// Output the changed Value
NSLog (@ "new musicName is % @", [change objectForKey: @ "new"]);

# Pragma mark-Memory Management
-(Void) dealloc {
// Remove the observer
[Music removeObserver: self forKeyPath: @ "musicName"];
[Music release];
[Super dealloc];


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: 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.