如何为一个实例动态替换方法?
#import "ViewController.h"
#import <objc/runtime.h>
@interface ViewController ()
@end
@implementation ViewController
+(void)load {
static dispatch_once_t onceToken; //必须只调用一次,如果调用偶数次,就会起不到交换的作用
dispatch_once(&onceToken,^{
SEL originSel = @selector(originFunc);
SEL swizzlingSel = @selector(swizzlingFunc);
Method originMethod = class_getInstanceMethod(self,originSel);
Method swizzlingMethod = class_getInstanceMethod(self, swizzlingSel);
BOOL methodAdded = class_addMethod(self, originSel, method_getImplementation(swizzlingMethod), method_getTypeEncoding(swizzlingMethod));
if(methodAdded) {
class_replaceMethod(self, swizzlingSel, method_getImplementation(originMethod), method_getTypeEncoding(originMethod));
} else{
method_exchangeImplementations(originMethod, swizzlingMethod);
}
});
}
- (void)viewDidLoad {
[super viewDidLoad];
[self originFunc];
}
-(void)originFunc {
NSLog(@"%s",__func__);
}
-(void)swizzlingFunc {
NSLog(@"%s",__func__);
}
@end
2017-03-24 21:50:37.911 ceshi3[8508:83721] -[ViewController swizzlingFunc]