Runtime应用之交换方法实现
2020-04-21 本文已影响0人
执笔时光er
Runtime一个常用的场景是交换方法的调用。其实就是利用了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+++++++++++");
}
核心思路是先找到对应的Method,然后将其交换就OK。
上面实现的是交换实例方法,如果交换类方法的话,会发现Method是nil,这是因为类方法是存储在类所对应的源类的,代码需要修改一下:
- (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+++++++++++");
}
核心还是先找到对应的Method,只不过类方法需要去到源类里面寻找,然后将其对应交换就OK。
我曾执笔雕刻时光 奈何良辰难书过往