• kvc


    - (void)viewDidLoad
    {
        [super viewDidLoad];
        [self createUI];
        
        xiaoCustom = [[Custom alloc]init];
        [xiaoCustom setValue:@"test" forKey:@"name"];
        [xiaoCustom setValue:[NSNumber numberWithInt:19] forKey:@"age"];
    
        //OC传统方法对成员变量赋值
        //使用点语法或者直接调用setter方法
    //    [xiaoCustom setName:@"test"];
    //    xiaoCustom.age = 19;
    //    //获取成员变量的值使用的就是点语法或者getter方法
    //    NSLog(@"%@,%d",[xiaoCustom name],xiaoCustom.age);
        //传统方法对成员属性进行赋值或者获取 必须确保成员变量setter和getter方法有声明和实现部分 才可以
        
        
        //OC新特性     先赋值 后获取
        //KVC (key-value-code) 键值编码
        //键指的就是成员变量的名称  值指的就是成员变量的值
        //通过KVC对成员变量进行赋值 setValue:forKey:
        //通过KVC对成员变量的获取 valueForKey:
        
        //KVC对成员属性进行赋值和获取 是动态进行的:
        //会先去成员变量所属的类中查找 是否实现了该成员变量的setter获取getter方法 如果没有实现 就是查找是否具有和当前变量同名的成员属性 如果成员属性也不存在 就会去查找是否具有_开头与该变量同名的成员属性名称 再找不到程序运行崩溃
    }
    -(void)createUI
    {
        UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake(50, 100, 200, 50)];
        label.backgroundColor = [UIColor cyanColor];
        label.tag = 1;
        [self.view addSubview:label];
        [label release];
        
        UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(100, 200, 100, 100);
        [btn addTarget:self action:@selector(pressBtn:) forControlEvents:UIControlEventTouchUpInside];
        [btn setTitle:@"获取" forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        [self.view addSubview:btn];
    
        NSString * string = [NSString stringWithFormat:@"name:,age:"];
        label.text = string;
    }
    -(void)pressBtn:(id)sender
    {
        UILabel * label = (UILabel *)[self.view viewWithTag:1];
        NSString * name = [xiaoCustom valueForKey:@"name"];
        
        int age = [[xiaoCustom valueForKey:@"age"]intValue];
        NSString * string = [NSString stringWithFormat:@"name:%@,age:%d",name,age];
        label.text = string;
    }
  • 相关阅读:
    Linux 常用命令
    silky微服务简介
    okhttp中的Builder模式
    Assert in C#&Java
    Abstract类中使用@Autowire
    @Scope("prototype") bean scope not creating new bean
    【转】centos系统查看cpu内存等情况
    hdu 7013 String Mod 题解
    牛客 11259 H Scholomance Academy 题解
    bzoj 2151 种树 题解
  • 原文地址:https://www.cnblogs.com/sayimba/p/5672904.html
Copyright © 2020-2023  润新知