KVC:key value coding    键值对的编码

功能:用来给对象属性设置值或者取出对象属性的值。虽然getter和setter方法也是该功能,但是如果类中没有设置属性特性或者重写这两个方法时,就无法存取属性值了。此时,采用KVC机制可以帮助完成这些要求。
 
先来个举例:给对象属性设值和取值
@interface Person
@property(strong,nonatomic)NSString name;
@end
一般模式:
Perosn *person = [[Person alloc]init];
[person setName:@“Tom”];
NSString *name = [person name];
 
KVC机制:
[perosn setValue:@“Tom” forKey:@“name”];
NSString *name = [person valueForKey:@“name”];
 
详细介绍:

@interface NSObject(NSKeyValueCoding)

//默认返回yes,如果没有setter方法,按_key,is_key,key,iskey的顺序搜索成员名

+ (BOOL)accessInstanceVariablesDirectly;

//通过属性的字符串键获取值

- (id)valueForKey:(NSString *)key;

//通过属性的字符串键设置值

-(void)setValue:(id)value forKey:(NSString*)key;

//通过属性路径字符串键获取值(格式:@“_xx._xx")

- (id)valueForKeyPath:(NSString *)keyPath;

//通过属性路径字符串键设置属性值(格式:@“_xx._xx")

- (void)setValue:(id)value forKeyPath:(NSString *)keyPath;

//通过属性字符串键检查值的正确性

- (BOOL)validateValue:(inout id *)ioValue forKey:(NSString *)inKey error:(out NSError **)outError;

//通过属性路径字符串键检查值的正确性

- (BOOL)validateValue:(inout id *)ioValue forKeyPath:(NSString *)inKeyPath error:(out NSError**)outError;

//通过属性数组键返回可变数组(有序一对多的关系:NSArray)

- (NSMutableArray *)mutableArrayValueForKey:(NSString *)key;

//通过属性数组路径键返回可变数组(有序一对多的关系:NSArray)

- (NSMutableArray *)mutableArrayValueForKeyPath:(NSString *)keyPath;

//通过属性集合键返回可变集合(无序一对多的关系:NSSet)

- (NSMutableSet *)mutableSetValueForKey:(NSString *)key;

//通过属性集合路径键返回可变集合(无序一对多的关系:NSSet)

- (NSMutableSet *)mutableSetValueForKeyPath:(NSString *)keyPath;

//通过数组(多个值)键获取字典值

- (NSDictionary *)dictionaryWithValuesForKeys:(NSArray *)keys;

//通过字典键设置多个值(数组)

- (void)setValuesForKeysWithDictionary:(NSDictionary *)keyedValues;

//通过属性字符串键返回可变有序集合

- (NSMutableOrderedSet *)mutableOrderedSetValueForKey:(NSString *)key;

//通过属性路径字符串键返回可变有序集合

- (NSMutableOrderedSet *)mutableOrderedSetValueForKeyPath:(NSString *)keyPath;

//当key不存在时,会处理异常,即会调用下面这两个方法(例如判断key==id时可以设取值)

- (id)valueForUndefinedKey:(NSString *)key;

- (void)setValue:(id)value forUndefinedKey:(NSString *)key;

//为nil设置一个合理的值,对于标量来说,多数情况下合理值为0

- (void)setNilValueForKey:(NSString *)key;

@end

@interface NSArray(NSKeyValueCoding)               //不可变数组

- (id)valueForKey:(NSString *)key;

- (void)setValue:(id)value forKey:(NSString *)key;

@end

@interface NSDictionary(NSKeyValueCoding)          //不可变字典

- (id)valueForKey:(NSString *)key;

@end

@interface NSMutableDictionary(NSKeyValueCoding)//可变字典

- (void)setValue:(id)value forKey:(NSString *)key;

@end

@interface NSOrderedSet(NSKeyValueCoding)       //有序set集合

- (id)valueForKey:(NSString *)key ;

- (void)setValue:(id)value forKey:(NSString *)key ;

@end

@interface NSSet(NSKeyValueCoding)                 //无序set集合

- (id)valueForKey:(NSString *)key;

- (void)setValue:(id)value forKey:(NSString *)key;

@end

具体的演示实例如下:

1、通过键访问属性:

首先创建一个Person类,perosn.h中声明person对象的属性姓名name,年龄age

#import <Foundation/Foundation.h>

@interface Person : NSObject
{
NSString *_name; //姓名
NSInteger _age; //年龄
}
@end

person.m中重写输出方法-(NSString*)description

#import "Person.h"

@implementation Person
-(NSString *)description
{
return [NSString stringWithFormat:@"name:%@,age:%ld",_name,_age];
}
@end

然后再main方法中设置属值性和取出属性值

#import <Foundation/Foundation.h>
#import "Person.h" int main(int argc, const char * argv[]) {
@autoreleasepool
{
//使用KVC来存取对象中的数据成员
Person *person = [[Person alloc]init]; [person setValue:@"Tom" forKey:@"_name"];
[person setValue:@ forKey:@"_age"]; NSLog(@"%@",person);
}
return ;
}

打印结果如下:

-- ::36.736 Person[:] name:Tom,age:
Program ended with exit code:

2、当对象中的数据成员如果是另一个对象,可以使用keyPath的键路径的形式访问这个对象中的数据成员

首先创建一个学生类Student,在Student.h中声明学生姓名、年龄、课程对象属性

#import <Foundation/Foundation.h>

@class Course;
@interface Student : NSObject
{
NSString *_name;
NSInteger _age;
Course *_course; //将课程对象定义为学生对象的属性
}
@end

然后再创建一个课程类Course,在Course.h中声明课程名属性

#import <Foundation/Foundation.h>

@interface Course : NSObject
{
NSString *_CourseName;

CGFloat _score;  //分数

}
@end

最后再main函数中实现KVC机制

#import <Foundation/Foundation.h>
#import "Student.h"
#import "Course.h" int main(int argc, const char * argv[]) {
@autoreleasepool
{ //创建学生对象
Student *stu = [[Student alloc]init]; //设置stu属性值
[stu setValue:@"Tom" forKey:@"_name"];
[stu setValue:@ forKey:@"_age"]; //通过键取出属性值
NSString *name = [stu valueForKey:@"_name"];
NSInteger age = [[stu valueForKey:@"_age"] integerValue]; NSLog(@"name:%@,age:%ld",name,age); //创建科目对象
Course *course = [[Course alloc]init]; //通过键设置course属性值
[course setValue:@"Chinese" forKey:@"_CourseName"];
[course setValue:@99.3 forKey:@"_score"];
[stu setValue:course forKey:@"_course"]; //通过键路径取出course属性值
NSString *courseName = [stu valueForKeyPath:@"_course._CourseName"];
CGFloat score = [[stu valueForKeyPath:@"_course._score"]floatValue]; NSLog(@"courseName:%@,score:%.1lf",courseName,score); //也可以使用键路径设置和取值
[stu setValue:@"English" forKeyPath:@"_course._CourseName"];
courseName = [stu valueForKeyPath:@"_course._CourseName"]; //将基本数据类型封装成字符串
[stu setValue:@"92.5" forKeyPath:@"_course._score"];
NSString *score2 = [stu valueForKeyPath:@"_course._score"]; NSLog(@"courseName:%@,score2:%@",courseName,score2);
}
return ;
}

打印结果如下:

-- ::38.412 KVC-键路径[:] name:Tom,age:
-- ::38.414 KVC-键路径[:] courseName:Chinese,score:99.3
-- ::38.414 KVC-键路径[:] courseName:English,score2:92.5
Program ended with exit code:

3、使用KVC操作数组:当对象中有一个数组属性时,也可以使用KVC机制访问数组中的数据

首先创建一个动物类Animal

在anmial.h文件中声明属性

#import <Foundation/Foundation.h>

@interface Animal : NSObject
{
NSString *_name; //名字
NSString *_food; //食物
NSArray *_otherAnimal; //其他动物数组
}
@end

在animal.m中重写输出方法-(void)description

#import "Animal.h"

@implementation Animal
-(NSString*)description
{
return [NSString stringWithFormat:@"name:%@,food:%@",_name,_food];
}
@end

在main主函数中进行KVC的操作

#import <Foundation/Foundation.h>
#import "Animal.h" int main(int argc, const char * argv[]) {
@autoreleasepool { //创建动物对象
Animal *animal = [[Animal alloc]init]; //设置属性
[animal setValue:@"Cat" forKey:@"_name"];
[animal setValue:@"fish" forKey:@"_food"]; //取出属性
NSString *animalName = [animal valueForKey:@"_name"];
NSString *foodName = [animal valueForKey:@"_food"]; NSLog(@"animalName:%@,foodName:%@",animalName,foodName); //其他的动物
Animal *animal2 = [[Animal alloc]init];
Animal *animal3 = [[Animal alloc]init];
Animal *animal4 = [[Animal alloc]init]; [animal2 setValue:@"dog" forKey:@"_name"];
[animal3 setValue:@"rabbit" forKey:@"_name"];
[animal4 setValue:@"pannada" forKey:@"_name"]; [animal2 setValue:@"gone" forKey:@"_food"];
[animal3 setValue:@"grass" forKey:@"_food"];
[animal4 setValue:@"bamboo" forKey:@"_food"]; NSArray *array = @[animal2,animal3,animal4]; [animal setValue:array forKey:@"_otherAnimal"]; //取出其他动物的属性
NSLog(@"%@",[animal valueForKey:@"_otherAnimal"]); //打印所有动物的所有信息
NSLog(@"%@",[animal valueForKeyPath:@"_otherAnimal.name"]);//输出所有动物的名字
NSLog(@"%@",[animal valueForKeyPath:@"_otherAnimal._food"]);//输出所有动物的食物
}
return ;
}

打印结果如下:

-- ::30.375 KVC-操作数组[:] animalName:Cat,foodName:fish
-- ::30.377 KVC-操作数组[:] (
"name:dog,food:gone",
"name:rabbit,food:grass",
"name:pannada,food:bamboo"
)
-- ::30.377 KVC-操作数组[:] (
dog,
rabbit,
pannada
)
-- ::30.377 KVC-操作数组[:] (
gone,
grass,
bamboo
)
Program ended with exit code:

Objective-C:KVC机制的更多相关文章

  1. ios使用kvc机制简化对json的解析

    在 ios开发中,我们经常需要对服务器的传回来的json进行解析,特别是对哪些字段特别多的就会又烦躁的情绪.tmd都是一样的东西,要为每个property赋值,真是累人啊.举个简单的例子吧.服务器会过 ...

  2. iOS编程——Objective-C KVO/KVC机制[转]

    这两天在看和这个相关的的内容,全部推翻重写一个版本,这是公司内做技术分享的文档总结,对结构.条理做了更清晰的调整.先找了段代码,理解下,网上看到最多的一段的关于KVC的代码 先上代码 1.     1 ...

  3. iOS编程——Objective-C KVO/KVC机制

    来源:http://blog.sina.com.cn/s/blog_b0c59541010151s0.html 这两天在看和这个相关的的内容,全部推翻重写一个版本,这是公司内做技术分享的文档总结,对结 ...

  4. IOS之KVC机制(Object-C篇)

    开发环境:xcode7 一.KVC概述 1.KVC是KeyValueCoding的简称,它是一种可以直接通过类属性的名字来作key,再绑定key的值来访问类属性的机制,而不再通过利用@property ...

  5. KVC该机制

    KVC该机制 KVC是cocoa的大招,用来间接获取或者改动对象属性的方式. 一.KVC的作用: KVC大招之中的一个: [self setValuesForKeysWithDictionary:di ...

  6. IOS学习之初识KVC

    什么是kvc? kvc (key-value coding )键值编码,是ios 提供的一种通过key间接的来访问对象属性的一直方式. 哪些类支持kvc操作? kvc的操作方法由NSKeyValueC ...

  7. KVC&&&KVO

    KVC 什么是KVC --->What KVC指的就是NSKeyValueCoding非正式协议. KVC是一种间接地访问对象的属性的机制. 这种间接表现在通过字符串来标识属性,而不是通过调用存 ...

  8. KVC与KVO的实现原理

    |KVC的用法 1.KVC既键值编码(Key Value Coding),基于NSKeyValueCoding协议,它是以字符串的形式来操作对象的成员变量,也就是通过字符串key来指定要操作的成员变量 ...

  9. KVO/KVC 实现机理分析

    来源:http://blog.csdn.net/dqjyong/article/details/7672865 Objective-C里面的Key-Value Observing (KVO)机制,非常 ...

随机推荐

  1. AtomicReference 和 volatile 的区别

    顾名思义,就是不会被打断!!!!!! https://www.cnblogs.com/lpthread/p/3909231.html java.util.concurrent.atomic工具包,支持 ...

  2. Math.random易于记忆理解

    产生随机数 Math.random*(Max-Min)+Min

  3. echarts画k线图

    var charset = echarts.init(document.getElementById("k_line")) $.get(k_line.url_A).done(fun ...

  4. ubuntu16.04编译安装GPAC

    参考:http://blog.csdn.net/tianlong_hust/article/details/9273875 1.获取gpac的源代码 sudo apt-get install subv ...

  5. gvim 编辑器配置

    "关才兼容模式 set nocompatible "模仿快捷键,如:ctrt+A 全选.Ctrl+C复制. Ctrl+V 粘贴等 source $VIMRUNTIME/vimrc_ ...

  6. 将cmake文件转化为vs方便代码阅读与分析

    下面通过“chengxuyuancc”同学的图来说明.通过cmake将winafl cmake编译方式转化为vs2015,方便源码阅读与分析. 1.到官网下载cmake软件.启动图形版 2.选择源码目 ...

  7. 17-7-20-electron中主进程和渲染进程区别与通信

    老规矩,先吐槽,再记录. 今天被上司教育了将近一个小时.因为之前自动更新的模块,我认为已经完成了,但是还有一些细节没有完善好,就一直一直的被教育~ 事情全部做完,提交以后关闭issue! electr ...

  8. Spring的远程调用

    Spring远程支持是由普通(Spring)POJO实现的,这使得开发具有远程访问功能的服务变得相当容易 四种远程调用技术: ◆ 远程方法调用(RMI) ◆ Caucho的Hessian和Burlap ...

  9. 【模拟退火】poj2069 Super Star

    题意:让你求空间内n个点的最小覆盖球. 模拟退火随机走的时候主要有这几种走法:①随机旋转角度. ②直接不随机,往最远的点的方向走,仅仅在尝试接受解的时候用概率.(最小圆/球覆盖时常用) ③往所有点的方 ...

  10. 【扫描线】Gym - 100781G - Goblin Garden Guards

    平面上有100000个哥布林和20000个圆,问你不在圆内的哥布林有多少个. 将每个圆从左到右切2r+1次,形成(2r+1)*2个端点,将上端点记作入点,下端点记作出点,再将这些点和那些哥布林一起排序 ...