KVC

k v c

pragma mark KVC---key value coding 键值编码

// kvc就是给类中的属性赋值
Teacher *tec = [[Teacher alloc]initWithName:@"liuxing" age:23 sex:@"M"];
NSLog(@"===%@",tec.name);
// 键值对赋值法
[tec setValue:@"w" forKey:@"sex"];
NSLog(@"%@",tec.sex);

// 通过key获取属性对应的值
[tec valueForKey:@"sex"];
NSLog(@"%@",tec.sex);

    [tec setValue:@"zhansan" forKey:@"name"];
    NSLog(@"%@",tec);

// 设置student属性的值
Student *stu = [[Student alloc]init];
[tec setValue:stu forKey:@"stu"];//属性名

     stu.name = @"haha";
    tec.student.name =@"haha";

// 通过路径赋值
[tec setValue:@"haha" forKeyPath:@"student.name"];//属性的路径

// 通过路径获取值
NSString *path= [tec valueForKeyPath:@"stu.name"];

//用字典来设置多个属性的值
NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@"name",@"liuxing",@"sex",@"M", nil];

    [tec setValuesForKeysWithDictionary:dic];//常用的方法,这个方法我们要自己在.m中去实现
    [tec setValue:@"123" forKey:@"name2"];
   NSLog(@"字典获取值 = %@",tec);

你可能感兴趣的:(KVC)