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/

你可能感兴趣的:(Runtime)