iOS利用runtime追踪对象的每一个方法
来源:互联网 发布:剑灵火炮兰捏脸数据 编辑:程序博客网 时间:2024/06/13 03:29
iOS利用runtime追踪对象的每一个方法
我们会用到runtime替换方法来监听某个方法的调用。例如,项目中每个Controller都直接继承了UIViewController,但是现在想监听每个Controller的viewDidAppear 和 viewDidDisappear,用法如下:
void qhd_exchangeInstanceMethod(Class class, SEL originalSelector, SEL newSelector) { Method originalMethod = class_getInstanceMethod(class, originalSelector); Method newMethod = class_getInstanceMethod(class, newSelector); if(class_addMethod(class, originalSelector, method_getImplementation(newMethod), method_getTypeEncoding(newMethod))) { class_replaceMethod(class, newSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod)); } else { method_exchangeImplementations(originalMethod, newMethod); }}@implementation UIViewController (Test)+ (void)load { qhd_exchangeInstanceMethod([self class], @selector(viewDidAppear:), @selector(qhd_viewDidAppear:)); qhd_exchangeInstanceMethod([self class], @selector(viewDidDisappear:), @selector(qhd_viewDidDisappear:));}- (void)qhd_viewDidAppear:(BOOL)animated { //[MobClick beginLogPageView:self.title]; [self qhd_viewDidAppear:animated];}- (void)qhd_viewDidDisappear:(BOOL)animated { //[MobClick endLogPageView:self.title]; [self qhd_viewDidDisappear:animated];}@end
最近产生了一个的想法:替换一个类的所有方法,每一个方法都打印一个log,看看调用顺序是怎样的,例如我想知道UIViewController在运行时到底都调用了哪些方法,包括私有方法。
思路是这样的:
1.通过class_copyMethodList得出一个类的所有方法。
2.通过method_getTypeEncoding和method_copyReturnType得出方法的参数类型和返回值。
3.创建出SEL和IMP,通过class_addMethod动态添加新方法。
4.通过交换的思想,在新方法里通过NSInvocation来调用原方法。
难点在于,新方法里面怎么把方法的“实现”(即IMP)绑定上,并且在“实现”里调用原方法。在runtime的头文件中Method的结构:
typedef struct objc_method *Method;struct objc_method { SEL method_name char *method_types IMP method_imp }
可以看到Method包含了是三个元素:一个SEL,一个char *,一个IMP。
SEL是方法名,char *是方法的类型,IMP就是实现的地址。
具体代码查看github:https://github.com/qhd/ANYMethodLog.git
1 0
- iOS利用runtime追踪对象的每一个方法
- 利用runtime追踪对象的每一个方法
- iOS 利用runtime关联对象
- ios 利用runtime 机制 交换系统内部方法的实现
- iOS runtime方法详解之对象关联
- iOS crash 崩溃问题的追踪方法
- iOS crash 崩溃问题的追踪方法
- iOS crash 崩溃问题的追踪方法
- iOS crash 崩溃问题的追踪方法
- iOS crash 崩溃问题的追踪方法
- iOS crash 崩溃问题的追踪方法
- iOS crash 崩溃问题的追踪方法
- iOS 利用runtime实现的Method Swizzling
- 利用runtime更改系统方法的实现
- 利用runtime更改系统方法的实现
- iOS UIFont字体大小适配,利用类别写简单的runtime替换方法
- iOS 对象的归档、解档 runtime
- iOS 简单的runtime替换方法
- 后台获取Form中的值
- get_browser()用法
- 实现Android后台发邮件
- C++ 深拷贝与浅拷贝
- 九度 oj 题目1480:最大上升子序列和
- iOS利用runtime追踪对象的每一个方法
- Android 日常开发总结的技术经验 60 条
- 为什么java bean里面不用基本类型作为字段?
- 笔记--Ubuntu 14.0.4下Mapbox源码分析1
- RestTemplate
- 3098: Hash Killer II
- 自定义Unity资源文件打开方式
- 转 Vpn L2TP/IPsec 需要打开 IPSEC Services 服务
- BZOJ1141: [POI2009]Slw