Runtime 实现方法替换

直接上代码

首先引入runtime头文件

```

#import

+(void)load

{

static dispatch_once_t onceToken;

dispatch_once(&onceToken, ^{

Class class = [self class];

swizzleMethod(class, @selector(touchbutton1:), @selector(touchbutton2:));

});

}

- (void)viewDidLoad {

[super viewDidLoad];

UIButton *button5 = [[UIButton alloc]initWithFrame:CGRectMake(220, 200, 100, 100)];

[button5 setTitle:@"4" forState:UIControlStateNormal];

button5.backgroundColor = [UIColor grayColor];

[button5 addTarget:self action:@selector(touchbutton1:) forControlEvents:UIControlEventTouchUpInside];

button5.tag = 5;

[button5 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];

[self.view addSubview:button5];

}

void swizzleMethod(Class class,SEL originalSelector,SEL swizzledSelector){

Method originalMethod = class_getInstanceMethod(class, originalSelector);

Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);

BOOL didAddMethod = class_addMethod(class, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod));

if (didAddMethod) {

class_replaceMethod(class, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));

}else {

method_exchangeImplementations(originalMethod, swizzledMethod);

}

}

-(void)touchbutton1:(UIButton *)sender

{

NSLog(@"******* 点击 11111********");

}

-(void)touchbutton2:(UIButton *)sender

{

NSLog(@"******* 点击 222222********");

}

```

这样就实现了 点击调用的button1方法 变为调用button2 方法啦  

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 转载:http://www.cocoachina.com/ios/20161102/17920.html 因为Ob...
    F麦子阅读 673评论 0 1
  • 本文转载自:http://yulingtianxia.com/blog/2014/11/05/objective-...
    ant_flex阅读 776评论 0 1
  • 转载:http://yulingtianxia.com/blog/2014/11/05/objective-c-r...
    F麦子阅读 760评论 0 2
  • 转至元数据结尾创建: 董潇伟,最新修改于: 十二月 23, 2016 转至元数据起始第一章:isa和Class一....
    40c0490e5268阅读 1,762评论 0 9
  • 我们常常会听说 Objective-C 是一门动态语言,那么这个「动态」表现在哪呢?我想最主要的表现就是 Obje...
    Ethan_Struggle阅读 2,230评论 0 7