8.10谈谈Cocoa大招kvc

来源:互联网 发布:宇宙是什么样的知乎 编辑:程序博客网 时间:2024/04/26 06:51

以前学kvc的时候,key-value-coding一直没什么感觉。最近咋项目中用到了kvc,才知道这才是真真的大招。

如果不用kvc,我们看看以下代码:

- (instancetype)initWithDict:(NSDictionary *)dict{    if (self = [super init]) {        _answer = dict[@"answer"];        _title = dict[@"title"];        _icon =dict[@"icon"];        _options = dict[@"options"];    }    return self;}

而如果用kvc赋值:

- (instancetype)initWithDict:(NSDictionary *)dict{    if (self = [super init]) {        [self setValuesForKeysWithDictionary:dict];    }    return self;}

是不是超简洁方便!

不仅仅如此!

KVC是用来间接获取或者修改对象属性的方式。

这里写图片描述
使用kvc在获取数值时,如果指定对象不包括keypath的“键名”,会自动进入内部查找,
如果取值的对象是一个数组,同样返回一个数组

- (instancetype)initWithDict:(NSDictionary *)dict{    self = [super init];    if (self) {//        [self setValuesForKeysWithDictionary:dict];        [self setValue:dict[@"title"] forKey:@"title"];        // dict[@"cars"]存放的是字典的数组        // 希望将字典的数组转换成HMCar模型的数组//        [self setValue:dict[@"cars"] forKey:@"cars"];        self.cars = [HMCar carsWithArray:dict[@"cars"]];    }    return self;}

总结:
它 是一种使用字符串标识符,间接访问对象属性的机制,它是很多技术的基础。主要的方法就两对方法:(setValue:forKey,valueForKey)、setValue:forKeyPath,valueForKeyPath)

除了一般的赋值和取值的方法,我们还可以用Key-Value-Coding(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] 分数:882012-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] 最高成绩:992012-07-20 16:09:17.107 objectiveC[2857:403] 最低成绩:652012-07-20 16:09:17.108 objectiveC[2857:403] 平均成绩:80.333333333333333333333333333333333333

复制代码

部分内容from:
http://www.cnblogs.com/stoic/archive/2012/07/20/2601315.html
http://www.cnblogs.com/jay-dong/archive/2012/12/13/2815778.html

0 0
原创粉丝点击