method

什么是method-swizzling?

4-5-1

简单来说就是修改两个选择器的方法实现。

代码实现

1
2
3
4
5
6
7
8
9
#import <Foundation/Foundation.h>

@interface RuntimeObject : NSObject

- (void)test;

- (void)otherTest;

@end
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21


+ (void)load
{
Method test = class_getInstanceMethod(self, @selector(test));
Method otherTest = class_getInstanceMethod(self, @selector(otherTest));
method_exchangeImplementations(test, otherTest);
}

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

- (void)otherTest
{
//这个self 实际调用test
[self otherTest];
NSLog(@"otherTest");
}

@end