[iOS] 监视某个VC生命周期函数
阿神
阿神 2017-04-18 09:32:34
0
2
677

RT 需求是我要创建一个桥接类。
我需要对一些VC的生命周期做一些监控,比如VC的viewWillAppear等生命周期函数执行完,执行我的方法。

目前已尝试过 协议 hook 但都不够实现我的需求。
协议 并不能强制要求所有这些VC实现这些生命周期方法。毕竟多人开发,如果有人疏漏,桥接功能出错。

hook 第一不够安全,和category重写一样,一个容易有坑,一个是还是无法强制要求这些写VC的人,会实现生命周期这些函数。

所以求助大神们有什么推荐、?

阿神
阿神

闭关修行中......

reply all(2)
巴扎黑

Use method swizzling, example:

#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];
        }));
    });

}
刘奇

Thank you for your answer

But why was it replaced multiple times? The code is as follows

@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];
        }));
    });
    
}

The log is as follows

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template