直接上代码:
- (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 运行时交换两个方法的实现,原文链接请点击