利用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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 转至元数据结尾创建: 董潇伟,最新修改于: 十二月 23, 2016 转至元数据起始第一章:isa和Class一....
    40c0490e5268阅读 1,757评论 0 9
  • 我们常常会听说 Objective-C 是一门动态语言,那么这个「动态」表现在哪呢?我想最主要的表现就是 Obje...
    Ethan_Struggle阅读 2,230评论 0 7
  • 继上Runtime梳理(四) 通过前面的学习,我们了解到Objective-C的动态特性:Objective-C不...
    小名一峰阅读 769评论 0 3
  • 这篇文章完全是基于南峰子老师博客的转载 这篇文章完全是基于南峰子老师博客的转载 这篇文章完全是基于南峰子老师博客的...
    西木阅读 30,589评论 33 466
  • 转载:http://yulingtianxia.com/blog/2014/11/05/objective-c-r...
    F麦子阅读 760评论 0 2