注意: 在OC中,使用了Copy、Create、New类型的函数,需要释放指针(ARC是管不了C函数)
1.获取成员变量列表
unsigned int count;
///获取成员变量列表
Ivar *ivarList = class_copyIvarList([self class], &count);
for(unsigned int i = 0; i < count; i++){
Ivar myIvar = ivarList[i];
const char *ivarName = ivar_getName(myIvar);
NSString *ivarNameStr = [NSString stringWithUTF8String:ivarName];
NSLog(@"成员变量:%d-%@",i,ivarNameStr);
}
free(ivarList);
2.获取属性列表
unsigned int count;
///获取属性列表
objc_property_t *propertyList = class_copyPropertyList([self class], &count);
for(unsigned int i = 0; i < count; i++){
const char *propertyName = property_getName(propertyList[i]);
NSString *propertyNameStr = [NSString stringWithUTF8String:propertyName];
NSLog(@"属性:%d-%@",i,propertyNameStr);
}
free(propertyList);
3.获取方法列表
unsigned int count;
///获取方法列表
Method *methodList = class_copyMethodList([self class], &count);
for(unsigned int i = 0; i < count; i++){
Method method = methodList[i];
SEL _Nonnull aSelector = method_getName(method);
NSString *methodName = NSStringFromSelector(aSelector);
NSLog(@"方法名称:%@",methodName);
}
free(methodList);
4.获取所遵循的协议列表
unsigned int count;
///获取所遵循的协议列表
__unsafe_unretained Protocol **protocolList = class_copyProtocolList([self class], &count);
for(unsigned int i = 0; i < count; i++){
Protocol *myProtocol = protocolList[i];
const char *protocolName = protocol_getName(myProtocol);
NSString *protocolNameStr = [NSString stringWithUTF8String:protocolName];
//NSSelectorFromString(protocolNameStr);
NSLog(@"获取到的协议方法:%@",protocolNameStr);
}
free(protocolList);
5.获取某个类的私有属性的值
有一个继承自UIView类的自定义view FilterView 作用是放置筛选条件里面有一个
@property (nonatomic, strong) NSMutableArray *buttons;
属性作为筛选item的UIButton的容器
现在从buttons属性中拿到放置筛选条件的UIButton数组
//获取FilterView的私有属性buttons的值
FilterView *attrMenu = [[FilterView alloc] init];
Ivar attrMenuBtnsIvar = class_getInstanceVariable([attrMenu class], "_buttons");
NSArray *attrButtonsArr = object_getIvar(attrMenu, attrMenuBtnsIvar);
NSLog(@"获取到的筛选条件button:%@", attrButtonsArr);
free(attrMenuBtnsIvar);
网友评论