我们使用第三方库,有时候需要获取其成员变量。方法如下:
导入runtime
#import <objc/runtime.h>
声明一个Person类
@interface Person : NSObject
{
NSString *address;
}
@property(nonatomic,strong)NSString *name;
@property(nonatomic,assign)NSInteger age;
@end
使用runtime获取私有属性
//遍历获取Person类所有的成员变量IvarList
- (void) getAllIvarList {
unsigned int methodCount = 0;
Ivar * ivars = class_copyIvarList([Person class], &methodCount);
for (unsigned int i = 0; i < methodCount; i ++) {
Ivar ivar = ivars[i];
const char * name = ivar_getName(ivar);
const char * type = ivar_getTypeEncoding(ivar);
NSLog(@"Person拥有的成员变量的类型为%s,名字为 %s ",type, name);
}
free(ivars);
}
打印结果如下:
2019-12-12 15:14:02.115744+0800 PersonRuntime[11576:1071364] Person拥有的成员变量的类型为@"NSString",名字为 address
2019-12-12 15:14:02.115902+0800 PersonRuntime[11576:1071364] Person拥有的成员变量的类型为@"NSString",名字为 _name
2019-12-12 15:14:02.115997+0800 PersonRuntime[11576:1071364] Person拥有的成员变量的类型为q,名字为 _age