这里使用到Runtime来修改.m文件中的私有变量,下面附上代码
Father *father = [Father new];
//count记录变量的数量IVar是runtime声明的一个宏
unsigned int count = 0;
// 获取类的所有属性变量
Ivar *members = class_copyIvarList([Father class], &count);
for (int i = 0; i < count; i++) {
Ivar ivar = members[i];
//将IVar变量转换为字符串,这里获得了属性名
const char *memberName = ivar_getName(ivar);
NSLog(@"%s", memberName);
Ivar m_name = members[0];
//修改属性值
object_setIvar(father, m_name, @"Zhangsan");
//打印后发现Father中name的值变为Zhangsan
NSLog(@"%@", [father description]);
}
输出结果
_name
name = Zhangsan