·您现在的位置: 云翼网络 >> 文章中心 >> 网站建设 >> app软件开发 >> IOS开发 >> iOS.OCKVC-键值编码

iOS.OCKVC-键值编码

作者:佚名      IOS开发编辑:admin      更新时间:2022-07-23

KVC 是key,value,coding的缩写,即键值编码。在iOS中,可以通过类的属性的名称(key),来间接访问对象的属性信息。

 

建一个工程,创建一个Person类,它有两个属性,name和age。

Person.h:

 

#import <Foundation/Foundation.h>

 @interface Person : NSObject

{

  NSString * name,age;

}

 @end

 

 

ViewController.h:

在ViewController.h文件中引入Person类头文件,ViewController有一个Person类型的属性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];

    //创建Person对象jay

    _jay=[[Person alloc]init];

 

    //通过key,value设置对象jay的信息

    [_jay setValue:@"纠结伦" forKey:@"name"];

    [_jay setValue:@"30" forKey:@"age"];

    

     //通过Person的属性访问jay这个对象的信息。

    NSLog(@"%@",[_jay valueForKey:@"name"]);

    NSLog(@"%@",[_jay valueForKey:@"age"]);

}

 打印结果:

2015-03-21 15:31:27.536 OMG[1677:116165] 纠结伦

2015-03-21 15:31:27.537 OMG[1677:116165] 30

 

  一个类(Person)的对象(jay)通过setValue:forKey语句,来设置对象属性的信息,其中Key就是类(person)的属性,也是该对象(jay)的属相,这里的key分别是name和age,通过key设置它们的信息。再通过对象调用valueforkey:语句可以访问到key对应的属性信息。