iOS:runtime实现方法交换

2016-06-06  本文已影响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机制

上一篇 下一篇

猜你喜欢

热点阅读