RT 需求是我要创建一个桥接类。我需要对一些VC的生命周期做一些监控,比如VC的viewWillAppear等生命周期函数执行完,执行我的方法。
目前已尝试过 协议 hook 但都不够实现我的需求。协议 并不能强制要求所有这些VC实现这些生命周期方法。毕竟多人开发,如果有人疏漏,桥接功能出错。
hook 第一不够安全,和category重写一样,一个容易有坑,一个是还是无法强制要求这些写VC的人,会实现生命周期这些函数。
所以求助大神们有什么推荐、?
闭关修行中......
Gunakan method swizzling, contoh:
method swizzling
#import "UIViewController+WJAdd.h" #import <objc/runtime.h> typedef void (* _IMP)(id,SEL,...); @implementation UIViewController (WJAdd) +(void)load { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ Method viewDidLoad=class_getInstanceMethod(self, @selector(viewDidLoad)); _IMP viewDidLoad_IMP=(_IMP)method_getImplementation(viewDidLoad); method_setImplementation(viewDidLoad, imp_implementationWithBlock(^(id target,SEL action){ viewDidLoad_IMP(target,@selector(viewDidLoad)); NSLog(@"%@ did load",target); [target dosomething]; })); }); }
Terima kasih atas jawapan anda
Tetapi mengapa ia diganti beberapa kali? Kodnya adalah seperti berikut
@implementation HookTest - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. } +(void)load { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ Method viewDidAppear=class_getInstanceMethod([HookTest class], @selector(viewDidAppear:)); _IMP viewDidAppear_IMP=(_IMP)method_getImplementation(viewDidAppear); method_setImplementation(viewDidAppear, imp_implementationWithBlock(^(id target,SEL action){ viewDidAppear_IMP(target,@selector(viewDidAppear:)); NSLog(@"%@ did load",target); // [target dosomething]; })); }); }
Log adalah seperti berikut
Gunakan
method swizzling
, contoh:Terima kasih atas jawapan anda
Tetapi mengapa ia diganti beberapa kali? Kodnya adalah seperti berikut
Log adalah seperti berikut