iOS Development--Practical articles &KVO and KVC detailed

Source: Internet
Author: User

KVO and KVC Detailed

Because OBJC is designed primarily based on Smalltalk, it has many dynamic features like Ruby and Python, such as dynamic typing, dynamic loading, dynamic binding, and so on. Today we highlight key-value coding (KVC), key-value monitoring (KVO) features in OBJC:

    1. Key value Encoding KVC
    2. Key-Value Monitoring KVO
key value Encoding KVC

We know that in C # you can read and write properties of an object by reflection, which is sometimes especially handy because you can use strings to dynamically control an object. In fact, because of the language characteristics of OBJC, you can perform dynamic read and write properties without any action on the root, which is the key Value Coding (abbreviated as KVC).

The operation method of KVC is provided by the Nskeyvaluecoding protocol, and NSObject implements this protocol, that is to say, almost all the objects in OBJC support KVC operation, the common KVC operation method is as follows:

    • Dynamic settings: SetValue: Attribute value forkey: property name (for simple Path),setValue: Property value Forkeypath: Property path (for compound path, For example, if person has an account type attribute, then Person.account is a composite attribute)
    • Dynamic read: valueforkey: Property name ,valueforkeypath: Property name (for compound path)
Key-value monitoring Kvo

We know that there is a two-way binding mechanism in WPF and Silverlight that, if the data model is modified, is immediately reflected in the UI view, similar to today's more popular MVVM design pattern-based front-end framework, such as Knockout.js. In fact, in OBJC Zhongyuan support this mechanism, it is called Key Value observing (abbreviated KVO). KVO is actually an observer pattern that makes it easy to separate the view component from the data model, and when the data model's property values change, the view component as the listener is fired, and the listener itself is invoked when fired. To implement KVO in OBJC, the Nskeyvalueobserving protocol must be implemented, but fortunately NSObject has implemented the protocol, so OBJC can be used by almost all KVO objects.

The common methods for using KVO operations in OBJC are as follows:

    • Register the listener for the specified key path: AddObserver:forKeyPath:options:context:
    • Delete the listener for the specified key path: removeobserver:forkeypath,removeObserver:forKeyPath:context:
    • Callback Listener: ObserveValueForKeyPath:ofObject:change:context:

The use of the KVO is also relatively straightforward:

    1. by AddObserver:forKeyPath:options:context: Registering listeners for the listener (which is usually the data model)
    2. Rewrite the listener's ObserveValueForKeyPath:ofObject:change:context: method

/*********************************kvc/kvo*******************************************/

KVC

KVC in the actual development of the most used places generally have two

    • Dictionary to model: But this has a limitation, if his property is also a model can not use this method, or can not be one of the corresponding time
    • Set the value of the corresponding property by the property key

Dictionary Turn Model:

1 #pragmaMark Simple Dictionary Turn model2Nsdictionary *dict = @{3                                @"name":@"Jack",4                                @" Money":@"20.7",5                                };6     7 [P setvaluesforkeyswithdictionary:dict];8NSLog (@"name =%@, Money =%f", P.name, P.money);9     Ten #pragmaMark Complex model OneNsdictionary *dict = @{ A                            @"name":@"Jack", -                            @" Money":@"20.7", -                            @"Dog" : @{ the                                    @"name":@"Wangcai", -                                    @" Price":@"10.8" -                                    }, -                            @"Books" : @[ +                                    @{ -                                        @"name":@"5-minute breakthrough iOS development", +                                        @" Price":@"19.8" A                                        }, at                                    @{ -                                        @"name":@"3-minute breakthrough iOS development", -                                        @" Price":@"24.8" -                                        }, -                                    @{ -                                        @"name":@"1-minute breakthrough iOS development", in                                        @" Price":@"29.8" -                                        } to                                    ] +                            }; - [P setvaluesforkeyswithdictionary:dict]; theNSLog (@"%@", p); *}

Set the value of the property:

1 #pragmaMark Single Value2P.name =@"LNJ";3P.money =99.8;4     5[P SetValue:@"LNJ"Forkey:@"name"];6[P setvalue:@ (99.8) Forkey:@" Money"];7NSLog (@"name =%@, Money =%f", P.name, P.money);8     9 #pragmaMark Multilayer AssignmentTen      OneP.dog = [XmgdogNew]; AP.dog.name =@"Wangcai"; -P.dog.price =998; -      the[P.dog SetValue:@"Wangcai"Forkey:@"name"]; -[P.dog setvalue:@ (998) Forkey:@" Price"]; -      -[P SetValue:@"Wangcai"Forkeypath:@"Dog.name"]; +[P setvalue:@ (998) Forkeypath:@"Dog.price"]; -NSLog (@"name =%@, Price =%f", P.dog.name, p.dog.price); +      A #pragmaMark Private Property at      -[P SetValue:@"LNJ"Forkeypath:@"_name"]; -[P setvalue:@ ( -) Forkeypath:@"_age"]; -      -NSLog (@"name =%@", p.name); -[P say];

KVO

1: Create an Object

1 icocos *stu = [[Icocos alloc] init]; 2

2: Registers the listener for the specified key path and modifies the corresponding properties

1 [stu addobserver:self Forkeypath:@ "score" options: Nskeyvalueobservingoptionnew | Nskeyvalueobservingoptionold Context:nil]; 2     3      - ; 4     5     ;

3: Delete listener for specified key path

1 #warning 2 The internal implementation principle is: The system will automatically generate a subclass for us, and then rewrite the subclass of the set method, in the Set method to notify the listener 3      - ; 4     [Stu removeobserver:self Forkeypath:@ "score"];

4: Callback Listener

1 -(voidID)objectvoid *) context2{3      NSLog (@ "keypath =%@, obj =%@, change =%@, context =%@"object
   
     change, context); 
    4 }
   

KVO internal Implementation Mechanism:

The system will automatically generate a subclass for us, and then rewrite the subclass's set method to notify the listener in the Set method

iOS Development--Practical articles &kvo and KVC detailed

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.