IOS中简单的KVC概念理解与应用

说到KVO,就不得不说KVC了,KVO是对键值对进行监视的观察者,而KVC是对兼职对进行更改的方法。

对于属性的赋值和取值方法,除了普通的=赋值方法以外,KVC就是另一种赋值方式了。 

而除了.取值方式以外还可以通过KVC进行取值方式。

KVC对应的方法有以下几种。

动态赋值:setValue:属性值 forKey:属性名(用于简单路径)setValue:属性值 forKeyPath:属性路径(用于复合路径,例如Person有一个Account类型的属性,那么person.account就是一个复合属性)

动态读取:valueForKey:属性名 valueForKeyPath:属性名(用于复合路径,对应上面的动态路径赋值)

下面我贴出整个代码段 如下:

    Student * student = [[Student alloc] init];
    [student setValue:@"张三" forKey:@"name"];
    NSString * name = [student valueForKey:@"name"];
    NSLog(@"学生姓名:%@",name);
1.以上是简单路径的赋值和读取方式的使用
    Course * course = [[Course alloc] init];
    [course setValue:@"语文" forKey:@"courseName"];
    [student setValue:course forKey:@"course"];
    NSString * courseName = [student valueForKeyPath:@"course.courseName"];
    NSLog(@"课程1:%@",courseName);
2.以上是复合路径读取方式使用
    [student setValue:@"数学课" forKeyPath:@"course.courseName"];
    courseName = [student valueForKeyPath:@"course.courseName"];
    NSLog(@"课程2:%@",courseName); 
3.以上是复合路径赋值和读取方式使用
    [student setValue:@"88" forKey:@"point"];
    NSString * point = [student valueForKey:@"point"];
    NSLog(@"分数:%@",point);
4.自动封装基本数据类型
    Student * student1 = [[Student alloc] init];
    Student * student2 = [[Student alloc] init];
    Student * student3 = [[Student alloc] init];
    
    [student1 setValue:@"78" forKey:@"point"];
    [student2 setValue:@"98" forKey:@"point"];
    [student3 setValue:@"60" 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"]); 
5.在Student类中加入数组NSArray,用来表示其他的学生。这样我们可以添加多个其他的学生,再用集合操作计算学生的分数,最高分,最低分,平均分等

最后,特别想说一下 ,做ios开发四年了 居然才第一次知道还能用otherStudent.@avg.point 这种方式求值 太丢人了我~~~~
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值