美文网首页
iOS runtime动态变量控制

iOS runtime动态变量控制

作者: Lambo316 | 来源:发表于2016-09-18 11:54 被阅读19次

    1.动态变量控制

    1> 、 首先创建一个Person类

    .h文件 .m文件

    2>、创建VC实现动态变量控制

    #import "oneViewController.h"#import "Person.h"#import@interface oneViewController ()

    @property (weak, nonatomic) IBOutlet UITextField *textfield;

    @property (nonatomic, strong) Person *person;

    @end

    @implementation oneViewController

    - (void)viewDidLoad {

    [super viewDidLoad];

    self.person = [Person new];

    _person.name = @"xiaoming";

    NSLog(@"XiaoMing first answer is %@",self.person.name);

    }

    - (void)sayName

    {

    unsigned int count = 0;

    Ivar *ivar = class_copyIvarList([self.person class], &count);//count获取Person的属性个数,为2;

    for (int i = 0; i<count; i++){

    Ivar var = ivar[i];

    const char *varName = ivar_getName(var);//获取属性名称

    NSString *proname = [NSString stringWithUTF8String:varName];//C字符串转换

    if ([proname isEqualToString:@"_name"]) {  //这里别忘了给属性加下划线,通过属性名称

    object_setIvar(self.person, var, @"daming");//object_setIvar(类名, 属性名称, 变更后的名称)

    break;

    }

    }

    NSLog(@"XiaoMing change name  is %@",self.person.name);//已成功通过runtime更改属性的值

    self.textfield.text = self.person.name;

    }

    3>、效果如下:


    相关文章

      网友评论

          本文标题:iOS runtime动态变量控制

          本文链接:https://www.haomeiwen.com/subject/xrwkjttx.html