iOS之runtime机制

只要做iOS开发的,我相信都知道Objective-C是 一门动态语言,这意味着它不仅需要一个编译器,也需要一个运行时系统来创建类和对象。了解runtime机制,能让我们更好的理解此语言、更好的理解运行时机制,还能帮助我们在系统层面解决一些问题,要了解runtime,首先要了解它的核心----消息传递。

消息的传递过程大致如下:
1、系统首先找到消息的接收对象,然后通过对象的isa找到它的类。
2、在它的类中查找method_list,是否有selector方法。
3、没有则查找父类的method_list。
4、找到对应的method,执行它的IMP。
5、转发IMP的return值。

下面是我使用的代码,使用该机制替换方法,监听界面的使用情况:

+ (void)hookUIViewController
{
    Method appearMethod = class_getInstanceMethod([self class], @selector(viewDidAppear:));
    Method hookMethod = class_getInstanceMethod([self class], @selector(hook_ViewDidAppear:));
    method_exchangeImplementations(appearMethod, hookMethod);
    
    Method disappearMethod = class_getInstanceMethod([self class], @selector(viewDidDisappear:));
    Method hookdisMethod = class_getInstanceMethod([self class], @selector(hook_viewDidDisappear:));
    method_exchangeImplementations(disappearMethod, hookdisMethod);
}

- (void)hook_ViewDidAppear:(BOOL)animated
{
    NSString *appearDetailInfo = [NSString stringWithFormat:@" %@ - %@", NSStringFromClass([self class]), @"didAppear"];
    NSLog(@"%@", appearDetailInfo);
    NSLog(@"%@",self.title);
    [self hook_ViewDidAppear:animated];
}

- (void)hook_viewDidDisappear:(BOOL)animated
{
    NSString *appearDetailInfo = [NSString stringWithFormat:@" %@ - %@", NSStringFromClass([self class]), @"disAppear"];
    NSLog(@"%@", appearDetailInfo);
    [self hook_viewDidDisappear:animated];
}

这里说的并不全面,只是针对项目中,需要使用HOOK使用的部分,后面再整理一个完整的runtime详解。

猜你喜欢

转载自blog.csdn.net/weixin_34160277/article/details/86869939