Runtime一個常用的場景是交換方法的調(diào)用示损。其實(shí)就是利用了Runtime的方法交換渗磅,具體代碼如下:
- (void)viewDidLoad {
[super viewDidLoad];
[self doExchange];
[ViewController doPrint1];
// Do any additional setup after loading the view.
}
-(void)doExchange{
Method originalMethod = class_getInstanceMethod([self class], @selector(doPrint1));
Method swizzledMethod = class_getInstanceMethod([self class], @selector(doPrint2));
method_exchangeImplementations(originalMethod, swizzledMethod);
}
+(void)doPrint1{
NSLog(@"print-----------");
}
+(void)doPrint2{
NSLog(@"print+++++++++++");
}
核心思路是先找到對應(yīng)的Method,然后將其交換就OK检访。
上面實(shí)現(xiàn)的是交換實(shí)例方法始鱼,如果交換類方法的話,會發(fā)現(xiàn)Method是nil脆贵,這是因?yàn)轭惙椒ㄊ谴鎯υ陬愃鶎?yīng)的源類的医清,代碼需要修改一下:
- (void)viewDidLoad {
[super viewDidLoad];
[self doExchange];
[ViewController doPrint1];
// Do any additional setup after loading the view.
}
-(void)doExchange{
Method originalMethod = class_getInstanceMethod(objc_getMetaClass("ViewController"), @selector(doPrint1));
Method swizzledMethod = class_getInstanceMethod(objc_getMetaClass("ViewController"), @selector(doPrint2));
method_exchangeImplementations(originalMethod, swizzledMethod);
}
+(void)doPrint1{
NSLog(@"print-----------");
}
+(void)doPrint2{
NSLog(@"print+++++++++++");
}
核心還是先找到對應(yīng)的Method,只不過類方法需要去到源類里面尋找卖氨,然后將其對應(yīng)交換就OK会烙。
我曾執(zhí)筆雕刻時光 奈何良辰難書過往