准备工作/生成一个Person类并定义一个属性name
@property (nonatomic, copy) NSString* name;
控制器中初始化Person
- (void)viewDidLoad {
[super viewDidLoad];
self.persion = [[Persion alloc] init];
self.persion.name = @"Runya";
NSLog(@"%@", self.persion.name);
}
使用runtime改变实例成员的值
- (void) rylsj_changeVarName {
/// 实例变量个数
unsigned int count = 0;
/// 获取所有的实例变量
Ivar* ivar = class_copyIvarList([self.persion class], &count);
/// 遍历
for (int i = 0; i < count; i++) {
/// 实例变量
Ivar var = ivar[i];
/// 实例变量名字
const char * varName = ivar_getName(var);
/// 转换成OC语音形式的
NSString* name = [NSString stringWithUTF8String:varName];
if ([name isEqualToString:@"_name"]) {
object_setIvar(self.persion, var, @"RunyaLsj");
break;
}
}
}