条件:ViewController在load方法内交换了viewDidLoad方法,但子类的viewDidLoad没有写[super viewDidLoad]
问:子类的viewDidLoad执行的是父类交换后的还是自己的?
答:只执行自己的,不会去找父类的方法。方法查找过程,自身实现的,不会去查找父类的。
//父类
@implementation ParentVC
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(@"======ParentVC======");
}
@end
// 方法交换
@implementation ParentVC (Catrgory)
+ (void)load {
Method origin = class_getInstanceMethod([self class], @selector(viewDidLoad));
Method swizz = class_getInstanceMethod([self class], @selector(llviewDidLoad));
BOOL didAdd = class_addMethod([self class], @selector(viewDidLoad), method_getImplementation(swizz), method_getTypeEncoding(swizz));
if (didAdd) {
class_replaceMethod([self class], @selector(llviewDidLoad), method_getImplementation(origin), method_getTypeEncoding(origin));
} else {
method_exchangeImplementations(origin, swizz);
}
}
- (void)llviewDidLoad {
NSLog(@"======ParentVC+Catrgory======");
}
@end
//子类
- (void)viewDidLoad {
NSLog(@"======Student======");
}
执行结果如下:
2020-12-15 20:01:56.121563+0800 test[90699:14720833] ======ParentVC+Catrgory======
//以下是子类调用打印
2020-12-15 20:02:06.133559+0800 test[90699:14720833] ======Student======
2020-12-15 20:02:06.133993+0800 test[90699:14720833] ======Student======
若子类代码修改如下:
//子类
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(@"======Student======");
}
2020-12-15 20:07:40.416351+0800 test[90724:14725040] ======ParentVC+Catrgory======
//以下是子类调用打印
2020-12-15 20:07:46.244325+0800 test[90724:14725040] ======ParentVC+Catrgory======
2020-12-15 20:07:46.244549+0800 test[90724:14725040] ======Student======
2020-12-15 20:07:46.244963+0800 test[90724:14725040] ======ParentVC+Catrgory======
2020-12-15 20:07:46.245082+0800 test[90724:14725040] ======Student======
网友评论