代码改变世界

ios - runtime运行时应用---交换方法

2016-05-06 00:51  菜鸟Alex  阅读(3369)  评论(0编辑  收藏  举报
  • runtime运行时用法之一 --- 交换类的方法,此处简单写了把系统的UIView的setBackgroundColor的方法换成了自定义的pb_setBackgroundColor
  • 首先创建UIView的分类
  • 在分类中导入头文件#import <objc/runtime.h>
  • 实现load类方法 --- 类被加载运行的时候就会调用
  • 分别获取系统setBackgroundColor方法 和自定义的 pb_setBackgroundColor 方法.然后交换
  • 在AFNetworking中也有应用,AFN中利用runtime将访问网络的方法做了替换,替换后可以监听网络连接状态
static inline void af_swizzleSelector(Class theClass, SEL originalSelector, SEL swizzledSelector) {
     Method originalMethod = class_getInstanceMethod(theClass, originalSelector);
     Method swizzledMethod = class_getInstanceMethod(theClass, swizzledSelector);
     method_exchangeImplementations(originalMethod, swizzledMethod);


#import "UIView+BlackView.h"

/** 导入头文件 */
#import <objc/runtime.h>


@implementation UIView (BlackView)



+(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]];
}

@end


  • 控制器中测试
  • 分别创建一个Button 以及一个 View 并且设置好颜色,看效果

- (void)viewDidLoad {
    [super viewDidLoad];

    UIButton * btn = [UIButton new];
    btn.backgroundColor = [UIColor blackColor];
    [self.view addSubview:btn];
    btn.frame = CGRectMake(0, 30, 200, 40);
    [btn setTitle:@"点击" forState:UIControlStateNormal];
    
    UIView * viw = [[UIView alloc] initWithFrame:CGRectMake(0, 100, 100, 100)];
    viw.backgroundColor = [UIColor blueColor];
    [self.view addSubview:viw];
    

}


  • 效果如下: