美文网首页
iOS:runtime实现方法交换

iOS:runtime实现方法交换

作者: 不简单的风度 | 来源:发表于2016-06-06 20:20 被阅读122次

    新建一个类别,导入#import <objc/runtime.h>
    + (void)load方法中写代码

    + (void)load
    {
        
        SEL orignsel  = @selector(setBackgroundColor:);
        SEL exchgesel = @selector(ly_setBackGroundColor:);
        
        
        Method originalM  = class_getInstanceMethod([self class], orignsel);
        Method exchangeM  = class_getInstanceMethod([self class], exchgesel);
        
        BOOL didAddMethod = class_addMethod([self class], orignsel, method_getImplementation(exchangeM), method_getTypeEncoding(exchangeM));
        if (didAddMethod)
        {
            class_replaceMethod([self class], exchgesel, method_getImplementation(originalM), method_getTypeEncoding(originalM));
        }
        else
        {
            method_exchangeImplementations(originalM, exchangeM);
        }
        
    }
    
    - (void)ly_setBackGroundColor:(UIColor *)color
    {
        [self ly_setBackGroundColor:[UIColor cyanColor]];
    }
    
    

    至于具体原理可去搜索runtime机制

    相关文章

      网友评论

          本文标题:iOS:runtime实现方法交换

          本文链接:https://www.haomeiwen.com/subject/zvhddttx.html