直接上代码:
~~~
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
Method m1 = class_getInstanceMethod([self class], @selector(testExchange1));
Method m2 = class_getInstanceMethod([self class], @selector(testExchange2));
IMP impM1 = method_getImplementation(m1);
IMP impM2 = method_getImplementation(m2);
[self testExchange1];
[self testExchange2];
method_setImplementation(m2, impM1);
method_setImplementation(m1, impM2);
[self testExchange1];
[self testExchange2];
}
- (void) testExchange1 {
NSLog(@"%s", __func__);
}
- (void) testExchange2 {
NSLog(@"%s", __func__);
}
~~~
输出:
~~~
2015-11-02 13:54:12.646 02-runtime[2592:71972] -[ViewController testExchange1]
2015-11-02 13:54:12.647 02-runtime[2592:71972] -[ViewController testExchange2]
2015-11-02 13:54:12.648 02-runtime[2592:71972] -[ViewController testExchange2]
2015-11-02 13:54:12.649 02-runtime[2592:71972] -[ViewController testExchange1]
~~~
另外还可以用method_exchangeImplementations 运行时交换两个方法的实现,[原文链接请点击](http://blog.csdn.net/lvdezhou/article/details/49585439)
- 前言
- object_getIvar
- object_getClass
- object_getClassName
- object_setClass
- object_isClass
- object_setIvar
- objc_getClass
- Too many arguments to function call...
- objc_msgSend
- class_copyIvarList和class_copyMethodList
- method_exchangeImplementations
- 运用SEL,运行时改变两个方法的实现
- class_getInstanceMethod和class_getClassMethod
- class_respondsToSelector
- Objective-C Runtime 运行时之三:方法与消息