Objective-C:KVC机制
KVC:key value coding 键值对的编码
@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机制的更多相关文章
- ios使用kvc机制简化对json的解析
在 ios开发中,我们经常需要对服务器的传回来的json进行解析,特别是对哪些字段特别多的就会又烦躁的情绪.tmd都是一样的东西,要为每个property赋值,真是累人啊.举个简单的例子吧.服务器会过 ...
- iOS编程——Objective-C KVO/KVC机制[转]
这两天在看和这个相关的的内容,全部推翻重写一个版本,这是公司内做技术分享的文档总结,对结构.条理做了更清晰的调整.先找了段代码,理解下,网上看到最多的一段的关于KVC的代码 先上代码 1. 1 ...
- iOS编程——Objective-C KVO/KVC机制
来源:http://blog.sina.com.cn/s/blog_b0c59541010151s0.html 这两天在看和这个相关的的内容,全部推翻重写一个版本,这是公司内做技术分享的文档总结,对结 ...
- IOS之KVC机制(Object-C篇)
开发环境:xcode7 一.KVC概述 1.KVC是KeyValueCoding的简称,它是一种可以直接通过类属性的名字来作key,再绑定key的值来访问类属性的机制,而不再通过利用@property ...
- KVC该机制
KVC该机制 KVC是cocoa的大招,用来间接获取或者改动对象属性的方式. 一.KVC的作用: KVC大招之中的一个: [self setValuesForKeysWithDictionary:di ...
- IOS学习之初识KVC
什么是kvc? kvc (key-value coding )键值编码,是ios 提供的一种通过key间接的来访问对象属性的一直方式. 哪些类支持kvc操作? kvc的操作方法由NSKeyValueC ...
- KVC&&&KVO
KVC 什么是KVC --->What KVC指的就是NSKeyValueCoding非正式协议. KVC是一种间接地访问对象的属性的机制. 这种间接表现在通过字符串来标识属性,而不是通过调用存 ...
- KVC与KVO的实现原理
|KVC的用法 1.KVC既键值编码(Key Value Coding),基于NSKeyValueCoding协议,它是以字符串的形式来操作对象的成员变量,也就是通过字符串key来指定要操作的成员变量 ...
- KVO/KVC 实现机理分析
来源:http://blog.csdn.net/dqjyong/article/details/7672865 Objective-C里面的Key-Value Observing (KVO)机制,非常 ...
随机推荐
- Mysql 数据库学习笔记01查询
1.数据查询基本操作 * 正则表达式查询: 字段名 regexp '匹配方式', select * from user where username regexp '^名' -- 查询 姓名 名 ...
- redis使用教程
一.redis 的安装 官方就是个坑:只说make一下即可用,确实可以用,我以为装好了,结果好多问题: 安装步骤:make => make test => make install 1 ...
- layui文件单文件和多文件的上传、预览以及删除和修改
活不多说,直接上代码 单文件上传 1.HTML <blockquote class="layui-elem-quote layui-quote-nm" style=" ...
- python写的的简单的爬虫小程序
import re import urllib def getHtml(url): page=urllib.urlopen(url) html=page.read() return html def ...
- python 函数的几个属性 func_name, func_code等
直接见代码: #!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2018/07/25 10:14 def add(x=0, y=1): & ...
- Android学习之Android studio篇-Android Studio快捷键总结(mac)
原文:http://blog.csdn.net/hudfang/article/details/52117065 符号代表键盘按键:⌘(command).⌥(option).⇧(shift).⇪(ca ...
- 感受C#6.0新语法
作为一门专为程(yu)序(fa)员(tang)考虑的语言,感受一下来自微软的满满的恶意... 1. 字符串内联在之前的版本中,常用的格式化字符串: var s = String.Format(&quo ...
- Bootstrap新版里的a标签点击后出现下划线解决办法
其实我从失去焦点后发现了下划线消失了就应该知道 Bootstrap对a标签进行了 focus焦点事件. 所以解决办法就是一句:a:focus{text-decoration: none}. 一个笑笑的 ...
- 不同版本的jquery的复选框checkbox的相关问题
在尝试写复选框时候遇到一个问题,调试了很久都没调试出来,极其郁闷: IE10,Chrome,FF中,对于选中状态,第一次$('#checkbox').attr('checked',true)可以实现 ...
- phpstorm中Xdebug的使用
目 录 1.Xdebug简介 2.Xdebug的安装.操作 2.1环境搭建 2.2配置php.ini 2.3配置PhpStorm 2.4配置PHP Debug 2.5进行调试 1.Xdebug简介 ...