unsigned int count;
//获取属性列表
objc_property_t *propertyList = class_copyPropertyList([Son class], &count);
for (unsigned int i=0; i<count; i++) {
const char *propertyName = property_getName(propertyList[i]);
NSLog(@"property---->%@", [NSString stringWithUTF8String:propertyName]);
}
unsigned int count;
//获取方法列表
Method *methodList = class_copyMethodList([Son class], &count);
for (unsigned int i = 0; i<count ; i++) {
Method method = methodList[i];
NSLog(@"method---->%@", NSStringFromSelector(method_getName(method)));
}
unsigned int count;
//获取成员变量列表
Ivar *ivarList = class_copyIvarList([Son class], &count);
for (unsigned int i = 0; i<count; i++) {
Ivar myIvar = ivarList[i];
const char *ivarName = ivar_getName(myIvar);
NSLog(@"Ivar---->%@", [NSString stringWithUTF8String:ivarName]);
}
unsigned int count;
//获取协议列表
__unsafe_unretained Protocol **protocolList = class_copyProtocolList([Son class], &count);
for (unsigned int i = 0 ; i<count; i++) {
Protocol *myProtocal = protocolList[i];
const char *protocolName = protocol_getName(myProtocal);
NSLog(@"protocol---->%@", [NSString stringWithUTF8String:protocolName]);
}
//方法交换
- (void)exchangeMethod {
//获得viewController的生命周期方法的selector
SEL systemSel = @selector(run);
//自己实现的将要被交换的方法的selector
SEL mySel = @selector(noRun);
//两个方法的Method
Method systemMethod = class_getInstanceMethod([self class], systemSel);
Method myMethod = class_getInstanceMethod([self class], mySel);
//首先动态添加方法,实现是被交换的方法,返回值表示添加成功还是失败
BOOL isAdd = class_addMethod([Son class], systemSel, method_getImplementation(myMethod), method_getTypeEncoding(myMethod));
if (isAdd) {
//如果成功,说明类中不存在这个方法的实现
//将被交换方法的实现替换到这个并不存在的实现
class_replaceMethod([Son class], mySel, method_getImplementation(systemMethod), method_getTypeEncoding(systemMethod));
}else{
//否则,交换两个方法的实现
method_exchangeImplementations(systemMethod, myMethod);
}
}
网友评论