运行时 方法替换的时候需要执行两步:
第一步:类获取实例方法(class_getInstanceMethod)
第二步:方法交换实现(method_exchangeImplementations)
OBJC_EXPORT Method _Nullable
class_getInstanceMethod(Class _Nullable cls, SEL _Nonnull name)
参数说明:
参数1 cls :为执行SEL的类
参数2 SEL:为要替换的方法
实例如下:
@implementation Person
-(void)methodOrgReplaceWithA:(int)a B:(int)b{
NSLog(@"I'm here");
}
-(void)methodDestReplaceWithA:(int)a B:(int)b{
NSLog(@"I'm here");
}
-(void)methodDestReplaceWithA:(int)a B:(int)b C:(int)c{
NSLog(@"I'm here");
}
+(void)load{
//获取源@selector方法
Method orgM = class_getInstanceMethod([self class], @selector(methodOrgReplaceWithA:B:));
//获取目标@selector方法
Method desM = class_getInstanceMethod([self class], @selector(methodDestReplaceWithA:B:C:));
method_exchangeImplementations(orgM, desM);
}
@end
注意:
- 1 交换的方法必须存在,否则交换不成功
- 2 交换的参数可以不一致,目标参数按照源参数顺序一一对应,参数按照:少的去掉,多的随机值分配
网友评论