iOS Method Swizzling方法替换

void swizzling_method(Class class,SEL orignSelector,SEL newSelector)
{
    Method originM = class_getInstanceMethod(class, orignSelector);
    Method newM = class_getInstanceMethod(class, newSelector);

    if (class_addMethod(class, orignSelector, method_getImplementation(newM), method_getTypeEncoding(newM)))
    {
        class_replaceMethod(class, newSelector, method_getImplementation(originM), method_getTypeEncoding(originM));
    }
    else
    {
        method_exchangeImplementations(originM, newM);
    }
}

首先从外部传进来你所要被替换和替换的selector,调用class_getInstanceMethod方法取到它们的method,在if判断里面,调用class_addMethod判断一下orignSelector是不是在这个类里面实现了,如果在其父类里实现了,那class_getInstanceMethod返回的是父类方法,那我们最后替换掉的是父类的方法,这并不是我们想要得到的结果。如果已经存在,再用method_exchangeImplementations方法用新方法替换掉原方法。

这个替换方法可以替换自定义的方法和系统方法。

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    NSLog(@"viewDidLoad");
}

- (void)swizzling_viewDidLoad
{
    NSLog(@"swizzling_viewDidLoad");
}

+ (void)load
{
    swizzling_method(self, @selector(test), @selector(swizzling_viewDidLoad));
}

比如我在一个ViewControl里面使用swizzling_viewDidLoad替换掉系统的viewDidLoad,运行一下程序
这里写图片描述
替换完成!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值