iOS开发- runtime方法交换
2020-08-06 本文已影响0人
Simple_Code
+ (void)load{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
Method originalMethod = class_getInstanceMethod([self class], @selector(originalMethod));
Method swizzlingMethod = class_getInstanceMethod([self class], @selector(swizzlingMethod));
BOOL isAdded = class_addMethod([self class], method_getName(originalMethod), method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
//添加不存在的方法,返回Yes;
if (isAdded)
{
NSLog(@"方法在原类中不存在,已经添加成功,用下面的方法替换其实现");
class_replaceMethod([self class], method_getName(originalMethod), method_getImplementation(swizzlingMethod), method_getTypeEncoding(swizzlingMethod));
}
else
{
NSLog(@"方法在原类中存在,用下面的方法交换其实现方法");
method_exchangeImplementations(originalMethod, swizzlingMethod);
}
NSLog(@"end");
});
}
- (void)originalMethod{
NSLog(@"原类中的方法");
}
- (void)swizzlingMethod{
NSLog(@"替换过的方法");
}