+ (void)load {
//1、单例,避免多次交互
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
Method oriMethod = class_getInstanceMethod(self, @selector(eat));
Method swiMethod = class_getInstanceMethod(self, @selector(swi_eat));
// 3、取得新方法swiMethod的实现和方法类型签名
//把新方法实现放到旧方法名中,此刻调用-eat就是调用-swi_eat
BOOL didAddMethod = class_addMethod(self, @selector(eat), method_getImplementation(swiMethod), method_getTypeEncoding(swiMethod));
if (didAddMethod) {
// 3.1、添加成功,当前类未实现,父类实现了-eat
// 此时不必做方法交换,直接将swiMethod的IMP替换为父类oriMethod的IMP即可
class_replaceMethod(self, @selector(swi_eat), method_getImplementation(oriMethod), method_getTypeEncoding(oriMethod));
}else{
// 3.2、正常情况,直接交换
method_exchangeImplementations(oriMethod, swiMethod);
}
});
}
网友评论