RunTime运行时之改变私有属性的值
2017-06-07 本文已影响0人
飘金
#import "ViewController.h"
#import <objc/runtime.h>
@interface ViewController (){
NSString *str1;
}
@property (nonatomic, copy) NSString *str2;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self changeVarVaule];
}
#pragma 改变属性值(私有和公开)
- (void)changeVarVaule{
unsigned int outCount = 0;
//获取所有属性列表(包括私有的)
Ivar *vars= class_copyIvarList([self class], &outCount);
for(int i = 0;i < outCount;i++){
//循环取出属性
Ivar var = vars[i];
if(i == 0){
//设置属性的值方式一
object_setIvar(self, var, @"piaojin1");
}else{
//设置属性的值方式二
const char *varName = ivar_getName(var);//获取属性名字
[self setValue:@"piaojin2" forKey:[NSString stringWithUTF8String:varName]];//通过KVC设置属性值
}
}
NSLog(@"str1:%@,str2:%@",str1,self.str2);
}
@end