您的位置:首页 > 其它

runtime——函数替换

2015-12-15 01:38 239 查看
#import "ViewController.h"

#import "FatherVC.h"

#import <objc/runtime.h>

@interface ViewController ()

@end

@implementation ViewController

static int flag = 0;

- (void)viewDidLoad {

[super viewDidLoad];

// Do any additional setup after loading the view, typically from a nib.

self.view.backgroundColor = [UIColor grayColor];

UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(0, 100, 100, 100)];

btn.center = self.view.center;

[btn setTitle:@"跳转" forState:UIControlStateNormal];

[btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];

[self.view addSubview:btn];

UIButton *btn3 = [[UIButton alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];

[btn3 addTarget:self action:@selector(btn2Click:) forControlEvents:UIControlEventTouchUpInside];

[btn3 setTitle:@"测试" forState:UIControlStateNormal];

[self.view addSubview:btn3];

}

-(void)viewDidAppear:(BOOL)animated

{

[super viewDidAppear:animated];

if (flag>0) {

Method method1 = class_getInstanceMethod([FatherVC class], @selector(btnClick:));

Method method2 = class_getInstanceMethod([self class], @selector(testFun));

method_exchangeImplementations(method1, method2); //pop回来时将交换的方法还原

}

flag++;

}

-(void)btn2Click:(UIButton *)btn

{

NSLog(@"%s",__func__);

FatherVC *vc = [[FatherVC alloc]init];

[vc btnClick:nil];

}

-(void)btnClick:(UIButton *)btn

{

unsigned int count = 0;

Method method1 = class_getInstanceMethod([FatherVC class], @selector(btnClick:));

Method method2 = class_getInstanceMethod([self class], @selector(testFun));

method_exchangeImplementations(method1, method2);//交换ViewController和FatherVC的方法

[self.navigationController pushViewController:[[FatherVC alloc]init] animated:YES];

}

-(void)testFun

{

NSLog(@"%s",__func__);

}

@end

#import "FatherVC.h"

@interface FatherVC ()

@end

@implementation FatherVC

- (void)viewDidLoad {

[super viewDidLoad];

// Do any additional setup after loading the view.

UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(0, 100, 50, 50)];

[btn setTitle:@"点击" forState:UIControlStateNormal];

[btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];

[self.view addSubview:btn];

self.view.backgroundColor = [UIColor greenColor];

}

-(void)btnClick:(UIButton *)btn

{

NSLog(@"%s",__func__);

}

@end

点击VIewController 的测试按钮->跳转->FatherVC的点击按钮->ViewController的测试按钮,打印结果:

2015-12-15 01:36:23.178 runtimeFun[37704:1035543] -[ViewController btn2Click:]

2015-12-15 01:36:23.179 runtimeFun[37704:1035543] -[FatherVC btnClick:]

2015-12-15 01:36:26.362 runtimeFun[37704:1035543] -[ViewController testFun]

2015-12-15 01:36:32.626 runtimeFun[37704:1035543] -[ViewController btn2Click:]

2015-12-15 01:36:32.626 runtimeFun[37704:1035543] -[FatherVC btnClick:]

FatherVC的btnClick:被替换成viewController的testFun方法。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: