1愕乎、class_addMethod 添加方法
@implementation ViewController
+ (void)load
{
//獲取實例方法中存在的方法
Method method = class_getInstanceMethod([self class], @selector(sayHello));
//添加一個方法personSayHello阵苇, 它的實現(xiàn)指向sayHello的實現(xiàn)
BOOL res = class_addMethod([self class], @selector(personSayHello), method_getImplementation(method), method_getTypeEncoding(method));
}
- (void)viewDidLoad
{
[super viewDidLoad];
[self performSelector:@selector(personSayHello)];
}
- (void)sayHello
{
NSLog(@"say hello");
}
log:
2018-09-30 15:25:07.935242+0800 method_test[55232:4354234] say goodbye
2 、class_replaceMethod 替換方法的實現(xiàn)
@implementation ViewController
+ (void)load
{
Method method = class_getInstanceMethod([self class], @selector(sayGoodBye));
//替換方法
class_replaceMethod([self class], @selector(sayHello), method_getImplementation(method), method_getTypeEncoding(method));
}
- (void)viewDidLoad
{
[super viewDidLoad];
[self sayHello];
}
- (void)sayHello
{
NSLog(@"say hello");
}
- (void)sayGoodBye
{
NSLog(@"say goodbye");
}
@end
log
2018-09-30 15:25:08.116772+0800 method_test[55232:4354234] say goodbye
3感论、method_exchangeImplementations 交換方法實現(xiàn)
@implementation ViewController
+ (void)load
{
Method sayGoodsByeMethod = class_getInstanceMethod([self class], @selector(sayGoodBye));
Method sayHelloMethod = class_getInstanceMethod([self class], @selector(sayHello));
//交換兩個方法
method_exchangeImplementations(sayHelloMethod, sayGoodsByeMethod);
}
- (void)viewDidLoad
{
[super viewDidLoad];
[self sayHello];
[self sayGoodBye];
}
- (void)sayHello
{
NSLog(@"say hello");
}
- (void)sayGoodBye
{
NSLog(@"say goodbye");
}
log:
2018-09-30 15:30:39.848247+0800 method_test[55294:4362459] say goodbye
2018-09-30 15:30:39.848388+0800 method_test[55294:4362459] say hello