0%

RunTime - 获取类的属性、方法列表、成员变量、协议名

获取一个类的属性列表

1
2
3
4
5
6
7
8
9
- (void)getPropertyList {
unsigned int count;
objc_property_t *propertys = class_copyPropertyList([self class], &count);
for (int i = 0; i < count; i ++) {
objc_property_t property = propertys[i];
NSLog(@"%s %s\n", property_getName(property), property_getAttributes(property));
}
free(propertys);
}

获取一个类的方法列表

1
2
3
4
5
6
7
8
9
- (void)getMethodList {
unsigned int count;
Method *methods = class_copyMethodList([self class], &count);
for (int i = 0; i < count; i ++) {
Method method = methods[i];
NSLog(@"%@ %u \n", NSStringFromSelector(method_getName(method)), method_getNumberOfArguments(method));
}
free(methods);
}

获取成员变量

1
2
3
4
5
6
7
8
9
- (void)getIvarList {
unsigned int count;
Ivar *ivars = class_copyIvarList([self class], &count);
for (int i = 0; i < count; i ++) {
Ivar ivar = ivars[i];
NSLog(@"%s %s \n", ivar_getName(ivar), ivar_getTypeEncoding(ivar));
}
free(ivars);
}

获取协议名

1
2
3
4
5
6
7
8
- (void)getProtocolList {
unsigned int count;
__unsafe_unretained Protocol **protocols = class_copyProtocolList([self class], &count);
for (int i = 0; i < count; i ++) {
NSLog(@"%s", protocol_getName(protocols[i]));
}
free(protocols);
}

Demo 地址

https://github.com/GhostClock/Runtime-Demo