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);
}
}
最后編輯于 :
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。