#import "ViewController.h"
#import <objc/runtime.h>
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//獲取方法所有名
[self getMethodName];
//添加方法
[self addMethod];
//替換方法
[self changeMethod];
//改變方法實現(xiàn)
[self changeMethodImpl];
//方法實現(xiàn)改變后調(diào)用實驗
[self method_1];
}
#pragma 獲取方法名
- (void)getMethodName{
void (*useMethod)(id,SEL);
unsigned int outCount = 0;
Method *methods = class_copyMethodList([self class], &outCount);
for(int i = 0;i < outCount;i++){
Method method = methods[i];
SEL sel = method_getName(method);
NSLog(@"%s",sel_getName(sel));
if(sel == @selector(method_1)){
useMethod = (void (*)(id,SEL))[self methodForSelector:sel];
useMethod(self,sel);
}
}
}
#pragma 添加方法
- (void)addMethod{
class_addMethod([self class], @selector(method::), (IMP)method_impl, "i@:i@");
//此時調(diào)用方法需要用performSelector,否則編譯器會報錯
[self performSelector:@selector(method::) withObject:@[@"piaojin",@(25)]];
}
#pragma 動態(tài)替換方法(也可以用于替換方法實現(xiàn))
- (void)changeMethod{
//method_1與method_2進行替換
method_exchangeImplementations(class_getInstanceMethod([self class], @selector(method_1)), class_getInstanceMethod([self class], @selector(method_2)));
}
#pragma 動態(tài)替換方法實現(xiàn)
- (void)changeMethodImpl{
//改變method_1的實現(xiàn)為method_3
class_replaceMethod([self class], @selector(method_1), (IMP)method_3, "");
}
- (void)method_1{
NSLog(@"method_1");
}
void method_impl(id self,SEL _cmd,NSString *str,int age){
NSLog(@"str:%@,age:%d",str,age);
}
- (void)method_2{
NSLog(@"method_2");
}
void method_3(){
NSLog(@"method_3");
}
@end
RunTime運行時之動態(tài)替換和改變方法實現(xiàn)
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
相關(guān)閱讀更多精彩內(nèi)容
- 關(guān)于IoC容器和控制反轉(zhuǎn)(也被稱為依賴注入)模式以及Spring IoC的應(yīng)用場景我在這里就不進行贅述了,下面直接...
- 具體原理一句兩句也說不清楚,網(wǎng)絡(luò)文章: http://www.cnblogs.com/skywang12345/p...
- 【2017年10月7日-007-12】 ——讀《戰(zhàn)勝華爾街》每周小結(jié)week5 彼得.林奇作為一個著名的基金管理人...