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>、效果如下:
网友评论