iOS KVC

KVC NSKeyValueCoding 一中非正式的 Protocol,提供一种机制来间接访问对象的属性。

通过一个实例来说明他的访问机制

teacher 类      .m文件中什么都不做

#import <Foundation/Foundation.h>

@interface Teacher : NSObject
@property(nonatomic,copy)NSString *name;
@property(nonatomic,strong)NSArray *studentArray;
@end

  学生类 .m文件中什么都不做

#import <Foundation/Foundation.h>
#import "Teacher.h"
@interface Student : NSObject
@property(nonatomic,copy)NSString *name;
@property(nonatomic,strong)Teacher *teacher;
@property(nonatomic,assign)float score;
@end

测试调用

  Teacher *teacher1 = [Teacher new];
    teacher1.name = @"袁世凯";
    
    //通过KVC的方式将teacher1的name取出来
    NSString *teacherName = [teacher1 valueForKey:@"name"];
    NSLog(@"老师原名称:%@",teacherName);
    
    //通过KVC的方式改变老师的名称
    [teacher1 setValue:@"蒋介石" forKey:@"name"];
    NSLog(@"老师现在的名称:%@",teacher1.name);
  Student *student1 = [Student new];
    student1.name = @"阎锡山";
    student1.teacher = teacher1;
    NSLog(@"阎锡山的老师:%@",teacher1.name);
    
    //通过KVC的方式给一个float 类型的属性“score”赋值
    [student1 setValue:@"89.23" forKey:@"score"];
    //从结果上看,将一个字符串类型的数据通过KVC的方式可以直接赋给float类型的属性
    //同理其他的基本数据类型也可以
    NSLog(@"阎锡山的军事课分数:%.2f",student1.score);
    
    //当然可以通过学生可以给他的一个“teacher”属性赋值
    //通过学生给他的“teacher”属性写的“name”属性赋值
    [student1 setValue:@"戴笠" forKeyPath:@"teacher.name"];
    NSLog(@"阎锡山的老师:%@",teacher1.name);
  Student *stu1 = [Student new];
    stu1.name = @"QQQ";
    stu1.score = 30;
    Student *stu2 = [Student new];
    stu2.name = @"WWW";
    stu2.score = 40;
    Student *stu3 = [Student new];
    stu3.name = @"EEE";
    stu3.score = 100;
    
    NSArray *array = @[stu1,stu2,stu3];
    [teacher1 setValue:array forKey:@"studentArray"];
    NSLog(@"学生名字:%@ 分数:%@",[teacher1 valueForKeyPath:@"studentArray.name"],[teacher1 valueForKeyPath:@"studentArray.score"]);
    //KVC这种方式操作数组,数组会直接将所有的学生的名字  放在一个另数组中然后输出  同理分数也是这样处理
NSLog(@"最高成绩:%@", [teacher1 valueForKeyPath:@"studentArray.@max.score"]); NSLog(@"最低成绩:%@", [teacher1 valueForKeyPath:@"studentArray.@min.score"]); NSLog(@"平均成绩:%@", [teacher1 valueForKeyPath:@"studentArray.@avg.score"]); NSLog(@"成绩总和:%@", [teacher1 valueForKeyPath:@"studentArray.@sum.score"]);
原文地址:https://www.cnblogs.com/Mgs1991/p/5146780.html