我们打开一个类(Class),这类无非就是包含:成员变量(Ivar)、属性(Property)、方法(Method)三部分.
我们可以通过Runtime底层可以获取到任意一个类Ivar,Property、Method,那应该如何获取那?
第一: 获取一个类下的成员变量(Ivar)
- (void)allIvarList{
unsigned int count = 0; // 成员变量数量
Ivar *ivars = class_copyIvarList([self class], &count);
for (NSInteger i=0; i<count; i++) {
const char *name = ivar_getName(ivars[i]);//变量的名
NSString *nameStr = [NSString stringWithUTF8String:name];
id value = [self valueForKey:nameStr];// 获取变量值
const char *type = ivar_getTypeEncoding(ivars[i]);// 取得变量类型
NSString *typeStr = [NSString stringWithUTF8String:type];
NSLog(@"%@--%@==%@",nameStr,value,typeStr);
}
}
第二: 获取一个类下的 property属性变量
- (void)allProperties{
unsigned int count = 0;
// 获取@property申明的属性
objc_property_t *properties = class_copyPropertyList([self class], &count);
for (NSInteger i=0; i<count; i++) {
//获取属性的名字
const char *name = property_getName(properties[i]);
/*
在声明property属性时,总会带上一些修饰词,比如 nonatomic、assign、strong..,还需要带上这个变量的数据类型比如 NSString、NSArray...,而这些信息都是附带在这个变量的属性里的,我们称这些信息为property的attributes
*/
const char *attribute = property_getAttributes(properties[i]);
NSString *nameStr = [NSString stringWithUTF8String:name];
NSString *attributeStr = [NSString stringWithUTF8String:attribute];
}
}
第三: 获取一个类下的方法(Method)
- (void)methodList{
unsigned int count = 0;
Method *methods = class_copyMethodList([self class], &count);
for (NSInteger i=0; i<count; i++) {
// 方法名
SEL sel = method_getName(methods[i]);
const char *name = sel_getName(sel);
NSString *nameStr = [NSString stringWithUTF8String:name];
NSLog(@"%@",nameStr);
}
}