IOS. OC.02 KVC-key value encoding, ios. oc.02kvc-key value

Source: Internet
Author: User

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.

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.