KVC、运行时结合访问类的属性

引入运行时头文件

#import <objc/runtime.h>

#import <objc/objc.h>

使用运行时获取类的属性,通过KVC访问类的内部属性。
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
40
41
42
43
UISearchBar * searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 100, 300, 100)];
[self.view addSubview:searchBar];
// 公开的属性
searchBar.placeholder = @"默认文字";
searchBar.prompt = @"prompt...";
searchBar.tintColor = [UIColor yellowColor];// 光标的颜色

//1. 运行时获取所有成员变量以及对应的类型
//存在一个UISearchBarTextField类的变量_searchField,猜测应该是显示文字的
[self getIvarsClassString:NSStringFromClass(UISearchBar.class)];
// UISearchBarTextField本身没有找到相关的属性
[self getIvarsClassString:@"UISearchBarTextField"];

//2. 运行时获取指定字符串对应的类的父类:UITextField
Class cls = class_getSuperclass(NSClassFromString(@"UISearchBarTextField"));
NSLog(@"%@", cls);
//3. 通过上一步可知UISearchBarTextField的父类为UITextField
UITextField * field = [searchBar valueForKey:@"_searchField"];
field.font = [UIFont systemFontOfSize:14.0];
field.textColor = [UIColor orangeColor];
//4. 同理可以获取UTextField的站位label:_placeholderLabel.textColor
[field setValue:[UIColor greenColor] forKeyPath:@"_placeholderLabel.textColor"];

//5. 3,4可以合并,释放注释查看
//[searchBar setValue:[UIColor purpleColor] forKeyPath:@"_searchField.placeholderLabel.textColor"];

// 运行时获取类的所有成员变量
- (void)getIvarsClassString:(NSString *)clsName{
if (!clsName) {
return;
}
unsigned int ivarCount = 0;
/*
An array of pointers of type Ivar describing the instance variables declared by the class. Any instance variables declared by superclasses are not included. 只返回本类的成员变量,不包含父类的。
*/
Ivar * ivars = class_copyIvarList(NSClassFromString(clsName), &ivarCount);
for (unsigned int i = 0; i < ivarCount; i++) {
Ivar ivar = ivars[i];
NSString * name = [NSString stringWithUTF8String:ivar_getName(ivar)];
NSString * type = [NSString stringWithUTF8String:ivar_getTypeEncoding(ivar)];
NSLog(@"ap--name:%@ type:%@",name, type);
}
}
起风了,您的支持将鼓励我继续创作!