转自:http://www.cnblogs.com/stoic/archive/2012/07/20/2601315.html

除了一般的赋值和取值的方法,我们还可以用Key-Value-Coding(KVC)键值编码来访问你要存取的类的属性。

下图来自苹果官网:

如何使用KVC存取对象属性呢?看个示例

1、使用KVC

定义一个Student类,继承于NSObject。

.h文件

#import <Foundation/Foundation.h>

@interface Student : NSObject
{
NSString *name;
}
@end

.m文件

#import "Student.h"

@implementation Student

@end

.m文件也没有实现。name属性没有加property,原来的访问方法就访问不了name属性了。怎么办呢?用kvc就可以了

#import "Student.h"

int main(int argc, const char * argv[])
{
@autoreleasepool {
Student *student = [[[Student alloc]init ]autorelease];
[student setValue:@"张三" forKey:@"name"];
NSString *name = [student valueForKey:@"name"];
NSLog(@"学生姓名:%@",name);
}
return 0;
}

打印结果:

2012-07-20 15:04:09.920 objectiveC[1977:403] 学生姓名:张三

张三 这个值存进去了,通过valueForKey取出来了。

如果存的时候key和类属性的名称不一致会怎么样呢?

代码改成

[student setValue:@"张三" forKey:@"name1"];

运行,程序崩溃 ,打印:

2012-07-20 15:09:40.432 objectiveC[2069:403] *** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<Student 0x106f14270> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key name1.'

提示没有这个name1 这个key。

2、键路径访问属性

如果访问这个类里中的属性中的属性呢?那就用到了键路径

关键字:键路径取值valueForKeyPath 键路径存值:forKeyPath

新建一个类Course,课程类,课程类有课程名称这个属性

.h文件

#import <Foundation/Foundation.h>

@interface Course : NSObject
{
NSString *CourseName;
}
@end

.m文件

#import "Course.h"

@implementation Course

@end

在Student中添加Course属性 ,student.h文件中代码如下:

#import <Foundation/Foundation.h>
@class Course;
@interface Student : NSObject
{
NSString *name;
Course *course;
}
@end

实现还是什么都没有,这里就不贴代码了

在main方法中,我们实验通过键路径访问Course中CourseName的属性

#import "Student.h"
#import "Course.h" int main(int argc, const char * argv[])
{
@autoreleasepool {
Student *student = [[[Student alloc]init ]autorelease];
[student setValue:@"张三" forKey:@"name"];
NSString *name = [student valueForKey:@"name"];
NSLog(@"学生姓名:%@",name); Course *course = [[[Course alloc]init] autorelease];
[course setValue:@"语文课" forKey:@"CourseName"];
[student setValue:course forKey:@"course"];
NSString *courseName = [student valueForKeyPath:@"course.CourseName"];
NSLog(@"课程名称:%@", courseName); //也可以这样存值
[student setValue:@"数学课" forKeyPath:@"course.CourseName"];
courseName = [student valueForKeyPath:@"course.CourseName"];
NSLog(@"课程名称:%@", courseName); }
return 0;
}

运行打印结果:

2012-07-20 15:33:51.902 objectiveC[2415:403] 学生姓名:张三

2012-07-20 15:33:51.904 objectiveC[2415:403] 课程名称:语文课

2012-07-20 15:33:51.904 objectiveC[2415:403] 课程名称:数学课

3、自动封装基本数据类型

我们在Student类中添加分数属性 NSInteger point;

.h文件

#import <Foundation/Foundation.h>
@class Course;
@interface Student : NSObject
{
NSString *name;
Course *course;
NSInteger point;
}
@end

.m文件不改变

#import "Student.h"
#import "Course.h" int main(int argc, const char * argv[])
{
@autoreleasepool {
Student *student = [[[Student alloc]init ]autorelease];
[student setValue:@"张三" forKey:@"name"];
NSString *name = [student valueForKey:@"name"];
NSLog(@"学生姓名:%@",name); Course *course = [[[Course alloc]init] autorelease];
[course setValue:@"语文课" forKey:@"CourseName"];
[student setValue:course forKey:@"course"];
NSString *courseName = [student valueForKeyPath:@"course.CourseName"];
NSLog(@"课程名称:%@", courseName); //也可以这样存值
[student setValue:@"数学课" forKeyPath:@"course.CourseName"];
courseName = [student valueForKeyPath:@"course.CourseName"];
NSLog(@"课程名称:%@", courseName); [student setValue:@"88" forKeyPath:@"point"];
NSString *point = [student valueForKey:@"point"];
NSLog(@"分数:%@", point); }
return 0;
}

打印结果:

2012-07-20 15:43:19.593 objectiveC[2533:403] 学生姓名:张三

2012-07-20 15:43:19.596 objectiveC[2533:403] 课程名称:语文课

2012-07-20 15:43:19.596 objectiveC[2533:403] 课程名称:数学课

2012-07-20 15:43:19.598 objectiveC[2533:403] 分数:88

我们用NSString*类型设置的属性值@"88",而我们的属性是NSInteger类型的,存取都没有问题。

4、操作集合

在Student类中加入数组NSArray,用来表示其他的学生。这样我们可以添加多个其他的学生,再用集合操作计算学生的分数,最高分,最低分,平均分等

#import <Foundation/Foundation.h>
@class Course;
@interface Student : NSObject
{
NSString *name;
Course *course;
NSInteger point;
NSArray *otherStudent;
}
@end

.m文件实现不变。

在main函数中添加三个学生,添加到数组中,然后求平均分,最高,最低分,学生数量

#import "Student.h"
#import "Course.h" int main(int argc, const char * argv[])
{
@autoreleasepool {
Student *student = [[[Student alloc]init ]autorelease];
[student setValue:@"张三" forKey:@"name"];
NSString *name = [student valueForKey:@"name"];
NSLog(@"学生姓名:%@",name); [student setValue:@"88" forKey:@"point"];
NSString *point = [student valueForKey:@"point"];
NSLog(@"分数:%@", point); Student *student1 = [[[Student alloc]init]autorelease];
Student *student2 = [[[Student alloc]init]autorelease];
Student *student3 = [[[Student alloc]init]autorelease];
[student1 setValue:@"65" forKey:@"point"];
[student2 setValue:@"77" forKey:@"point"];
[student3 setValue:@"99" forKey:@"point"];
NSArray *array = [NSArray arrayWithObjects:student1,student2,student3,nil];
[student setValue:array forKey:@"otherStudent"];
NSLog(@"其他学生的成绩%@", [student valueForKeyPath:@"otherStudent.point"]);
NSLog(@"共%@个学生", [student valueForKeyPath:@"otherStudent.@count"]);
NSLog(@"最高成绩:%@", [student valueForKeyPath:@"otherStudent.@max.point"]);
NSLog(@"最低成绩:%@", [student valueForKeyPath:@"otherStudent.@min.point"]);
NSLog(@"平均成绩:%@", [student valueForKeyPath:@"otherStudent.@avg.point"]);
}
return 0;
}

运行打印结果

2012-07-20 16:09:17.101 objectiveC[2857:403] 学生姓名:张三

2012-07-20 16:09:17.104 objectiveC[2857:403] 分数:88

2012-07-20 16:09:17.105 objectiveC[2857:403] 其他学生的成绩(

    65,

    77,

    99

)

2012-07-20 16:09:17.106 objectiveC[2857:403] 3个学生

2012-07-20 16:09:17.106 objectiveC[2857:403] 最高成绩:99

2012-07-20 16:09:17.107 objectiveC[2857:403] 最低成绩:65

2012-07-20 16:09:17.108 objectiveC[2857:403] 平均成绩:80.333333333333333333333333333333333333

还可以求总和  @sum。

Objective-C语法之KVC使用的更多相关文章

  1. OC:属性、点语法、KVC

    //属性的属性 属性定义在一个 .h文件里,在这个.h文件里可以定义实例变量(就是这个类的特征),也可以通过   @protery(属性约束关键字) 属性名字类型 属性名 来定义一些属性,在prope ...

  2. 初学Objective - C语法之代码块(block)

    一.block声明 1.无参数,无返回值: void (^sayHi)(); 2.有参数,有返回值: NSInteger (^operateOfValue)(NSInteger num); block ...

  3. [转] 从 C 到 Objective C 入门1

    转自: http://blog.liuhongwei.cn/iphone/objective-c/ 进军iPhone开发,最大的难点之一就是怪异的Objective C语法了.不过,了解之后才发现,原 ...

  4. Key-Value-Coding(KVC)

    Objective-C语法之KVC的使用   除了一般的赋值和取值的方法,我们还可以用Key-Value-Coding(KVC)键值编码来访问你要存取的类的属性. 下图来自苹果官网: 如何使用KVC存 ...

  5. iOS开发——语法篇OC篇&高级语法精讲二

    Objective高级语法精讲二 Objective-C是基于C语言加入了面向对象特性和消息转发机制的动态语言,这意味着它不仅需要一个编译器,还需要Runtime系统来动态创建类和对象,进行消息发送和 ...

  6. iOS开发之---KVC全解

    ————————————————————————————————————————————————————————————— 一 KVC的基本概念 KVC是Key Value Coding的缩写,意思是 ...

  7. iOS开发之KVC全解

    一  KVC的基本概念 1.KVC是Key Value Coding的缩写,意思是键值编码. 在iOS中,提供了一种方法通过使用属性的名称(也就是Key)来间接访问对象属性的方法,这个方法可以不通过g ...

  8. ios开发runtime学习五:KVC以及KVO,利用runtime实现字典转模型

    一:KVC和KVO的学习 #import "StatusItem.h" /* 1:总结:KVC赋值:1:setValuesForKeysWithDictionary实现原理:遍历字 ...

  9. iOS知识点、面试题 之二

    最近面试,与大家分享一下,分三文给大家: 当然Xcode新版本区别,以及iOS新特性 Xcode8 和iOS 10 在之前文章有发过,感兴趣的可以查阅: http://www.cnblogs.com/ ...

随机推荐

  1. electron的通信

    1.获取当前设备的屏幕可用区域的分辨率winW=electron.screen.getPrimaryDisplay().workAreaSize.widthwinH=electron.screen.g ...

  2. Permission denied (publickey). fatal: The remote end hung up unexpectedly 解决办法

    这两天学习git的时候,在本地创建了一个库,同时自己在GitHub上面也创建了一个库,照着廖老师的教程一步一步走到了push的环节突然出现了这样的错误: [zhangxiyu@localhost le ...

  3. 在shell 中字符串,文件,数字的比较

    hadoop fs -test -e /path/exist ] ;then echo 'exist' else echo 'Error! path is not exist' fi 在shell中如 ...

  4. 【C#/WPF】.Net生成二维码QRCode的工具

    先马 http://qrcodenet.codeplex.com/ 使用该工具WPF生成二维码的简单例子: 前台XAML准备一个Image控件显示二维码. string qrcodeStr = &qu ...

  5. C语言 · 输出日历

    算法提高 输出日历   时间限制:1.0s   内存限制:512.0MB      按照下述格式打印2006年12月日历: Calendar 2006-12---------------------- ...

  6. java中的方法——重载yu重写(转)

    重载(Overloading) (1) 方法重载是让类以统一的方式处理不同类型数据的一种手段.多个同名函数同时存在,具有不同的参数个数/类型. 重载Overloading是一个类中多态性的一种表现. ...

  7. 打开wps的宏设置,提示你可能没有装vba

    打开wps的宏设置,提示你可能没有装vba?? 因为wps个人版没有vba,安装以下软件即可,亲测可行 VBA6.3提取自WPS2012专业增强版.zip   链接: http://pan.baidu ...

  8. zoj3228 Searching the String AC自动机查询目标串中模式串出现次数(分可覆盖,不可覆盖两种情况)

    /** 题目:zoj3228 Searching the String 链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=34 ...

  9. hadoop的调试

    折腾hadoop的调试很久了,一直都没折腾对,查过很多资料,但是都没试出来,最终在不断地尝试当中调试出来了,所以想把这个过程记录下来,和大家分享一下. 调试分为两部分,MapReduce的调试和源码的 ...

  10. CF555B 贪心

    http://codeforces.com/problemset/problem/555/B B. Case of Fugitive time limit per test 3 seconds mem ...