美文网首页
runtime拦截系统方法

runtime拦截系统方法

作者: 百无一用是码农 | 来源:发表于2017-02-23 15:21 被阅读0次

昨天朋友问我,怎么截取系统方法,第一个反应是使用父类,但是后来想了一下,这样处理的话又太过屌丝,后来上网一番查找,终于找到了。可以使用runtime进行方法截取。

替换的方法必须是在一个一定可以执行的方法中,而且方法最好只执行一次。这样的方法首选为:+ (void)load;这个方法为加载到内存的时候调用的,可以保证一定执行。

创建类目UIViewController (Category),在类目中进行处理。代码如下:

//这个是必不可少的

#import <objc/runtime.h>

@implementationUIViewController (Category)

+ (void)load

{

staticdispatch_once_tonceToken;

dispatch_once(&onceToken, ^{

MethodorigMethod =class_getInstanceMethod([selfclass],@selector(viewDidLoad));

MethodswizMethod=class_getInstanceMethod([selfclass],@selector(IncreasePageStatistics));

method_exchangeImplementations(origMethod, swizMethod);

});

}

- (void)IncreasePageStatistics

{

NSLog(@"---%@",NSStringFromClass(self.class));

return[self IncreasePageStatistics];

}

这是一个简单的在所以控制器上打印一句话的方法,避免了在所有控制器上编写代码的繁琐。

这种方式需要注意几点信息:

1.增加的函数(方法)与目标函数(方法)必须同种类型,都是加号方法或者都是减号方法;

2.两个方法的返回值必须是同种类型,必须是一样的返回值;

3.两个方法的参数必须是同种类型同样的个数。

如果符合这三个条件的话会替换不成功的。

相关文章

网友评论

      本文标题:runtime拦截系统方法

      本文链接:https://www.haomeiwen.com/subject/yokbwttx.html