IOS. OC.02 KVC-key value encoding, ios. oc.02kvc-key value
KVC is the abbreviation of key, value, and coding, that is, key-value encoding. In iOS, You can indirectly access the property information of an object through the class attribute name (key.
Create a project and create a Person class. It has two attributes: name and age.
Person. h:
# Import <Foundation/Foundation. h>
@ Interface Person: NSObject
{
NSString * name, age;
}
@ End
ViewController. h:
Introduce the Person Class header file in the ViewController. h file. ViewController has a Person type attribute jay.
# Import <UIKit/UIKit. h>
# Import "Person. h"
@ Interface ViewController: UIViewController
@ Property (nonatomic, retain) Person * jay;
@ End
ViewController. m:
# Import "ViewController. h"
@ Interface ViewController ()
@ End
@ Implementation ViewController
-(Void) viewDidLoad {
[Super viewDidLoad];
// Create the Person object jay
_ Jay = [[Person alloc] init];
// Set the information of the jay object through key and value
[_ Jay setValue: @ "tangle Lun" forKey: @ "name"];
[_ Jay setValue: @ "30" forKey: @ "age"];
// Access the information of the jay object through the Person attribute.
NSLog (@ "% @", [_ jay valueForKey: @ "name"]);
NSLog (@ "% @", [_ jay valueForKey: @ "age"]);
}
Print result:
15:31:27. 536 OMG [1677: 116165]Tangle Lun
15:31:27. 537 OMG [1677: 116165] 30
The object (jay) of a class (Person) uses the setValue: forKey statement to set the information of the object attribute. The Key is the property of the class (person) and is also the property of this object (jay) the key here is the name and age respectively, and their information is set through the key. Call valueforkey through an object: The statement can access the attribute information corresponding to the key.