方法调配(method swizzling)

http://www.cocoachina.com/ios/20141002/9819.html

http://blog.sina.com.cn/s/blog_a343f32b0101en4o.html

OC 是一门及其动态的语言,在运行期间,可以动态给某个对象添加方法,并且还可以改变某个方法实现

我们可以用此特性来干点坏事

通过这个特性,我们可以不需要继承子类,就可以改变这个类本身的一些功能,经常需要统计每个页面浏览的次数

这时我们一般是基于基类baseViewController 在viewWillAppear里统计,但这需要控制器都要继承它

我们可以直接用该技术,来拦截ViewWillAppear方法,在此方法里面去添加统计功能,但此项技术一般只是在调试的时候用

 1 #import "UIViewController+Swizzle.h"
 2 #import <objc/runtime.h>
 3 @implementation UIViewController (Swizzle)
 4 + (void)load{
 5     [super load];
 6     static dispatch_once_t onceToken;
 7     dispatch_once(&onceToken, ^{
 8         SEL old = @selector(viewWillAppear:);
 9         SEL newSelecotr  = @selector(xxx_viewWillAppear:);
10         Method oldm = class_getInstanceMethod([UIViewController class], old);
11         Method newm = class_getInstanceMethod([UIViewController class], newSelecotr);
12         BOOL didAddMethod  = class_addMethod([UIViewController class], old, method_getImplementation(newm ), method_getTypeEncoding(newm));
13         if (didAddMethod) {
14             class_replaceMethod([UIViewController class], newSelecotr, method_getImplementation(oldm), method_getTypeEncoding(oldm));
15         }else{
16             method_exchangeImplementations(oldm, newm);
17         }
18     });
19 }
20 
21 - (void)xxx_viewWillAppear:(BOOL)animated{
22     [self xxx_viewWillAppear:animated];
23     NSLog(@"do things");
24 }

 

 

 

 

 

posted on 2015-05-31 20:32  listener~  阅读(122)  评论(0编辑  收藏  举报

导航