• KVC


    KVC (key value coding)键值编码

    先定义两个类,person,dog

    1 @interface Dog : NSObject
    2 @property (nonatomic,copy) NSString *name;
    3 @end
     1 #import <Foundation/Foundation.h>
     2 @class Dog;
     3 
     4 @interface Person : NSObject
     5 @property (nonatomic,copy) NSString *name;
     6 @property (nonatomic,assign) int age;
     7 @property (nonatomic,copy) NSString *phone;
     8 @property (nonatomic,strong) Dog *dog;
     9 
    10 @end
     1   //实例化两个person
     2         Person *p = [[Person alloc]init];
     3         Person *p1= [[Person alloc]init];
     4         //实例化dog
     5         Dog *d = [[Dog alloc] init];
     6         p.dog = d;
     7         
     8         NSArray *pArray = @[p,p1];
     9         
    10 
    11         // 1.给p.name赋值
    12         [p setValue:@"Tom" forKey:@"name"];
    13         
    14         // 2.用字典给p的属性赋值,类的属性必须在字典中key存在,可以比字典中得key多,但是不能少。
    15         [p setValuesForKeysWithDictionary:@{@"name":@"Jack",@"age":@10,@"phone":@"24234232"}];
    16         
    17         NSDictionary *dict = @{@"name":@"Cruise",@"age":@12,@"phone":@"123214wrew"};
    18         
    19         [p1 setValuesForKeysWithDictionary:dict];
    20         
    21        
    22         // 3.按照键值路径赋值
    23         [p setValue:@"fuck" forKeyPath:@"dog.dogName"];
    24         
    25         // 4.KVC按照键值路径取值时,如果对象不包含指定的键值,会自动进入对象内部,查找对象属性
    26         NSArray *a = [pArray valueForKeyPath:@"name"];
    27         
    28         NSLog(@"%@",a);
    29         
    30         NSLog(@"%@ ,name= %@,age = %d,phone = %@,dogname = %@",p,p.name,p.age,p.phone,p.dog.dogName);

    输出结果:2014-05-25 19:49:26.634 xcode 小技巧- 自定义代码块[832:303] (
        Jack,
        Cruise
    )
    2014-05-25 19:49:26.641 xcode 小技巧- 自定义代码块[832:303] <Person: 0x100202d50> ,name= Jack,age = 10,phone = 24234232,dogname = fuck

    com.nigo
  • 相关阅读:
    zfs
    targetcli
    targetcli
    自动制linux iso包
    yum解决重复包,依赖冲突问题
    lvm相关
    vmware相关
    配置本地yum源
    k8s安装prometheus监控
    流水线基础-Pipeline
  • 原文地址:https://www.cnblogs.com/delegate/p/3751511.html
Copyright © 2020-2023  润新知