OC方法转化

2017-10-12  本文已影响10人  zelo

在OC编码中,有一种黑魔法,当你想截获一个方法,想在这个方法中添加一点你需要的东西,但是又不能改这个这个方法。可以利用runtime中的方法获取这个方法,通过方法转换,把你的方法插入到这个方法中去。

    //
    SEL originalSelector = @selector(actionForLayer:forKey:);
    SEL extendedSelector = @selector(DR_actionForLayer:forKey:);

    Method originalMethod = class_getInstanceMethod(self, originalSelector);
    Method extendedMethod = class_getInstanceMethod(self, extendedSelector);

    NSAssert(originalMethod, @"original method should exist");
    NSAssert(extendedMethod, @"exchanged method should exist");

    if(class_addMethod(self, originalSelector, method_getImplementation(extendedMethod), method_getTypeEncoding(extendedMethod))) {
        class_replaceMethod(self, extendedSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
    } else {
        method_exchangeImplementations(originalMethod, extendedMethod);
    }

或者用下面的方法

 +(void)load{
    /** 获取原始setBackgroundColor方法 */
    Method originalM = class_getInstanceMethod([self class], @selector(setBackgroundColor:));

    /** 获取自定义的pb_setBackgroundColor方法 */
    Method exchangeM = class_getInstanceMethod([self class], @selector(pb_setBackgroundColor:));

    /** 交换方法 */
    method_exchangeImplementations(originalM, exchangeM);
    
}
    
    
    
    /** 自定义的方法 */
-(void)pb_setBackgroundColor:(UIColor *) color{

    NSLog(@"%s",__FUNCTION__);

    /** 
     1.更改颜色
     2.所有继承自UIView的控件,设置背景色都会设置成自定义的'orangeColor'
     3. 此时调用的方法 'pb_setBackgroundColor' 相当于调用系统的 'setBackgroundColor' 方法,原因是在load方法中进行了方法交换.
     4. 注意:此处并没有递归操作.
     */
    [self pb_setBackgroundColor:[UIColor orangeColor]];
}

上一篇下一篇

猜你喜欢

热点阅读