IOS中简单的KVC概念理解与应用
2015-10-13 15:37
232 查看
说到KVO,就不得不说KVC了,KVO是对键值对进行监视的观察者,而KVC是对兼职对进行更改的方法。
对于属性的赋值和取值方法,除了普通的=赋值方法以外,KVC就是另一种赋值方式了。
而除了.取值方式以外还可以通过KVC进行取值方式。
KVC对应的方法有以下几种。
动态赋值:setValue:属性值
forKey:属性名(用于简单路径)、setValue:属性值
forKeyPath:属性路径(用于复合路径,例如Person有一个Account类型的属性,那么person.account就是一个复合属性)
动态读取:valueForKey:属性名 、valueForKeyPath:属性名(用于复合路径,对应上面的动态路径赋值)
下面我贴出整个代码段
如下:
最后,特别想说一下 ,做ios开发四年了 居然才第一次知道还能用otherStudent.@avg.point 这种方式求值 太丢人了我~~~~
对于属性的赋值和取值方法,除了普通的=赋值方法以外,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 这种方式求值 太丢人了我~~~~
相关文章推荐
- ios--apns Device token的获得和改变详解
- IOS 开发过程中的 消息通知 小红点
- iOS--xib界面与和代码相关联
- iOS开发过程中的各种坑
- 2015年最新苹果开发者账号注册流程详解
- PhoneGap/Cordova插件开发入门(IOS版)(一)
- ios推送 程序未启动,收到推送消息,打开应用后跳转到相应的活动页面的代码。
- iOS 按钮小知识点总结
- 在ios中开发使用自动布局约束小注意点。
- IOS远程推送(转载)
- iOS ViewController生命周期
- NSPredicate 模糊、精确、查询
- iOS中的动画
- iOS 9 适配
- IOS 在功能 autorelease release
- 在iOS开发中如何裁剪一个圆图像
- iOS英语—》中国本土化,如调用专辑,摄像头的变化“cancel”,“photos”至“撤消”,“摄像头”
- iOS 多线程开发
- 用segmentedControl控制显示n个页面之一(思想、思路、无代码)--iOS开发
- IOS中简单的KVO概念理解与应用