Runtime — Method Swizzling(修改系统方法的实现)

Method Swizzling是改变一个selector的实际实现的技术。通过这一技术,我们可以在运行时通过修改类的分发表中selector对应的函数,来修改方法的实现。

例如,我们想给UIButton 的点击事件加上一个延时调用并且有好多地方用到延时,如果自己写个延时你都会在每个button 中调用那样我就是有重复的代码

这种情况下,我们就可以使用Method Swizzling

  • (void)load{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
    SEL selA = @selector(sendAction:to:forEvent:);
    SEL selB = @selector(mySendAction:to:forEvent:);
    Method methodA = class_getInstanceMethod(self,selA);
    Method methodB = class_getInstanceMethod(self, selB);
    BOOL isAdd = class_addMethod(self, selA, method_getImplementation(methodB), method_getTypeEncoding(methodB));
    if (isAdd) {
    class_replaceMethod(self, selB, method_getImplementation(methodA), method_getTypeEncoding(methodA));
    }else{
    method_exchangeImplementations(methodA, methodB);
    }
    });
    }

//自定义的方法
- (void)mySendAction:(SEL)action to:(id)target forEvent:(UIEvent *)event
{

if ([NSStringFromClass(self.class) isEqualToString:@"UIButton"]) {

    if (self.isIgnoreEvent){
        NSLog(@"2222");
        return;
    }

    if (self.timeInterval > 0)
    {
        self.isIgnoreEvent = YES;
        [self performSelector:@selector(setIsIgnoreEvent:) withObject:@(NO) afterDelay:self.timeInterval];
    }
}
[self mySendAction:action to:target forEvent:event];

}

更多详细的内容参考:http://blog.jobbole.com/79580/

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值