class_addMethod、class_replaceMet
2018-09-30 本文已影响95人
淡燃
1、class_addMethod 添加方法
@implementation ViewController
+ (void)load
{
//获取实例方法中存在的方法
Method method = class_getInstanceMethod([self class], @selector(sayHello));
//添加一个方法personSayHello, 它的实现指向sayHello的实现
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 替换方法的实现
@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 交换方法实现
@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