首先甩出苹果官方文档的链接https://developer.apple.com/reference/objectivec/1418769-method_exchangeimplementations?language=objc
苹果为运行时交换方法提供了两种方法,如下
先创建一个类(eg:TestClass)
在.h文件里面声明两个方法
#import <Foundation/Foundation.h>
@interface TestClass : NSObject
- (void)testMethod1;
- (void)testMethod2;
@end
在.m文件里面实现两个方法
#import "TestClass.h"
@implementation TestClass
- (void)testMethod1{
NSLog(@"这是测试类的实例方法---1");
}
- (void)testMethod2{
NSLog(@"这是测试类的实例方法+++2");
}
@end
注意:testMethod1打印的是 @”这是测试类的实例方法—1”
testMethod2打印的是 @”这是测试类的实例方法+++2”
第一种运行时交换方法的方法
void method_exchangeImplementations(Method m1, Method m2);
- (void)firstExchangeMethod {
TestClass *test = [[TestClass alloc]init];
[test testMethod1];
NSLog(@"----------交换方法前后的分割线----------");
Method T1 = class_getInstanceMethod([TestClass class], @selector(testMethod1));
Method T2 = class_getInstanceMethod([TestClass class], @selector(testMethod2));
method_exchangeImplementations(T1, T2);
[test testMethod1];
}
打印结果如图:
第二种运行时交换方法的方法:
IMP imp1 = method_getImplementation(m1);
IMP imp2 = method_getImplementation(m2);
method_setImplementation(m1, imp2);
method_setImplementation(m2, imp1);
- (void)secondExchangeMethod{
TestClass *test = [[TestClass alloc]init];
[test testMethod1];
NSLog(@"----------交换方法前后的分割线----------");
Method m1 = class_getInstanceMethod([TestClass class], @selector(testMethod1));
Method m2 = class_getInstanceMethod([TestClass class], @selector(testMethod2));
IMP imp1 = method_getImplementation(m1);
IMP imp2 = method_getImplementation(m2);
method_setImplementation(m1, imp2);
method_setImplementation(m2, imp1);
[test testMethod1];
}
打印结果如下: