RunTime运行时之改变私有属性的值

RunTime运行时之改变私有属性的值


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#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

------本文结束😘感谢阅读------