runtime方法交换

方法交换的作用:
一、在不修改源代码的基础上,对方法内的代码进行修改
二、

- (void)viewDidLoad {
[super viewDidLoad];
objc_msgSend(self,@selector(test));

[self say];
[self mySay];

[self changeMethod];

[self say];
[self mySay];
}

- (void)test
{
    NSLog(@"test");
}

- (void)changeMethod
{
    /*
     class_getInstanceMethod     得到类的实例方法
     class_getClassMethod          得到类的类方法
     */
    Method say1 = class_getInstanceMethod([ViewController    class], @selector(say));
    Method mySay1 = class_getInstanceMethod([ViewController class], @selector(mySay));
    method_exchangeImplementations(say1, mySay1);
}

- (void)say
{
     NSLog(@"%s",__FUNCTION__);
}

- (void)mySay
{
    NSLog(@"%s",__FUNCTION__);
}

测试结果:
2016-08-11 16:17:16.997 RuntimeTest[3199:126416] test
2016-08-11 16:17:16.997 RuntimeTest[3199:126416] -    [ViewController say]
2016-08-11 16:17:16.997 RuntimeTest[3199:126416] - [ViewController mySay]
2016-08-11 16:17:16.998 RuntimeTest[3199:126416] -[ViewController mySay]
2016-08-11 16:17:16.998 RuntimeTest[3199:126416] -[ViewController say]

你可能感兴趣的:(runtime方法交换)