原文地址:http://www.jianshu.com/p/f6300eb3ec3dhtml
以前在项目中有遇到过用runtime
解决改变全局字体的问题,因此再一次感觉到了runtime
黑魔法的强大,趁如今有机会分享一下对runtime
的一些理解。
在对象调用方法是Objective-C
中常用的功能,也就是消息的传递,而Objective-C
是C
的超集,因此和C
不一样的是,Objective-C
使用的是动态绑定,也就是runtime
。Objective-C
的消息传递和消息机制也就很少说了,今天主要说的是动态方法,也就是函数的调用。markdown
下面一张图详细的归纳了每一个函数调用的前后以及执行的前提app
+ (BOOL)resolveInstanceMethod:(SEL)sel
ide
这个方法在运行时,没有找到SEL
的IM
L时就会执行。这个函数是给类利用class_addMethod
添加函数的机会。根据文档,若是实现了添加函数代码则返回YES
,未实现返回NO
。
举个例子,新建了一个工程,首先我在ViewController
这个类中执行doSomething1
这个方法,代码以下函数
// // ViewController.m // RuntimeTest1 // // Created by HenryCheng on 15/12/24. // Copyright © 2015年 www.igancao.com All rights reserved. // #import "ViewController.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; [self performSelector:@selector(doSomething)]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end
运行结果字体
**2015-12-24 10:35:37.726 RuntimeTest1[1877:337842] -[ViewController doSomething]: unrecognized selector sent to instance 0x7fe9f3736680** **2015-12-24 10:35:37.729 RuntimeTest1[1877:337842] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[ViewController doSomething]: unrecognized selector sent to instance 0x7fe9f3736680'** ***** First throw call stack:**
不出意外,程序崩溃,由于没有找到doSomething
这个方法,下面咱们在里面实现 + (BOOL)resolveInstanceMethod:(SEL)sel
这个方法,而且判断若是SEL
是doSomething
那就输出add method here
ui
// // ViewController.m // RuntimeTest1 // // Created by HenryCheng on 15/12/24. // Copyright © 2015年 www.igancao.com All rights reserved. // #import "ViewController.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; [self performSelector:@selector(doSomething)]; } + (BOOL)resolveInstanceMethod:(SEL)sel { if (sel == @selector(doSomething)) { NSLog(@"add method here"); return YES; } return [super resolveInstanceMethod:sel]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end
继续运行,而后看到log
this
**2015-12-24 10:47:24.687 RuntimeTest1[2007:382077] add method here** **2015-12-24 10:47:24.687 RuntimeTest1[2007:382077] -[ViewController doSomething]: unrecognized selector sent to instance 0x7f9568c331f0** **2015-12-24 10:47:24.690 RuntimeTest1[2007:382077] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[ViewController doSomething]: unrecognized selector sent to instance 0x7f9568c331f0'** ***** First throw call stack:**
能够看到程序依然是崩溃了,可是咱们能够看到输出了add method here
,这说明咱们 + (BOOL)resolveInstanceMethod:(SEL)sel
这个方法执行了,并进入了判断,因此,在这儿,咱们能够作一下操做,使这个方法获得相应,不至于走到最后- (void)doesNotRecognizeSelector:(SEL)aSelector
这个方法中而崩掉了,接下来,我么继续操做,以下spa
// // ViewController.m // RuntimeTest1 // // Created by HenryCheng on 15/12/24. // Copyright © 2015年 www.igancao.com All rights reserved. // #import "ViewController.h" #import <objc/runtime.h> @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; [self performSelector:@selector(doSomething)]; } + (BOOL)resolveInstanceMethod:(SEL)sel { if (sel == @selector(doSomething)) { NSLog(@"add method here"); class_addMethod([self class], sel, (IMP)dynamicMethodIMP, "v@:"); return YES; } return [super resolveInstanceMethod:sel]; } void dynamicMethodIMP (id self, SEL _cmd) { NSLog(@"doSomething SEL"); } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end
导入了<objc/runtime.h>
而且在+ (BOOL)resolveInstanceMethod:(SEL)sel
中执行了class_addMethod
这个方法,而后定义了一个void dynamicMethodIMP (id self, SEL _cmd)
这个函数,运行工程,看log
3d
**2015-12-24 11:45:11.934 RuntimeTest1[2284:478571] add method here** **2015-12-24 11:45:11.934 RuntimeTest1[2284:478571] doSomething SEL**
这时候咱们发现,程序并无崩溃,并且还输出了doSomething SEL
,这时候就说明咱们已经经过runtime
成功的向咱们这个类中添加了一个方法。关于class_addMethod
这个方法,是这样定义的
OBJC_EXPORT BOOL class_addMethod(Class cls, SEL name, IMP imp, const char *types)
cls
在这个类中添加方法,也就是方法所添加的类name
方法名,这个能够随便起的imp
实现这个方法的函数types
定义该数返回值类型和参数类型的字符串,这里好比"v@:"
,其中v
就是void
,带表返回类型就是空,@
表明参数,这里指的是id(self)
,这里:
指的是方法SEL(_cmd)
,好比我再定义一个函数
int newMethod (id self, SEL _cmd, NSString *str) { return 100; }
那么添加这个函数的方法就应该是ass_addMethod([self class], @selector(newMethod), (IMP)newMethod, "i@:@");
+ (BOOL)resolveInstanceMethod:(SEL)sel
中没有找到或者添加方法消息继续往下传递到- (id)forwardingTargetForSelector:(SEL)aSelector
看看是否是有对象能够执行这个方法,咱们来从新建个工程,而后新建一个叫SecondViewController
的类,里面有一个- (void)secondVCMethod
方法,以下
// // SecondViewController.m // RuntimeTest2 // // Created by HenryCheng on 15/12/24. // Copyright © 2015年 www.igancao.com All rights reserved. // #import "SecondViewController.h" @interface SecondViewController () @end @implementation SecondViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. } - (void)secondVCMethod { NSLog(@"This is secondVC method !"); } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } /* #pragma mark - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ @end
工程结构应该是这样的
如今我想在ViewController
中调用- (void)secondVCMethod
这个方法,咱们知道ViewController
和SecondViewController
并没有继承关系,按照正常的步骤去作程序确定会由于在ViewController
找不到- (void)secondVCMethod
这个方法而直接崩溃的
// // ViewController.m // RuntimeTest2 // // Created by HenryCheng on 15/12/24. // Copyright © 2015年 www.igancao.com All rights reserved. // #import "ViewController.h" #import <objc/runtime.h> @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; [self performSelector:@selector(secondVCMethod)]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end
运行结果
**2015-12-24 13:54:44.314 RuntimeTest2[3164:835814] -[ViewController secondVCMethod]: unrecognized selector sent to instance 0x7fc3a8535c10** **2015-12-24 13:54:44.317 RuntimeTest2[3164:835814] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[ViewController secondVCMethod]: unrecognized selector sent to instance 0x7fc3a8535c10'** ***** First throw call stack:**
如今咱们来处理一下这个消息,以下
// // ViewController.m // RuntimeTest2 // // Created by HenryCheng on 15/12/24. // Copyright © 2015年 www.igancao.com All rights reserved. // #import "ViewController.h" #import <objc/runtime.h> @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; [self performSelector:@selector(secondVCMethod)]; } - (id)forwardingTargetForSelector:(SEL)aSelector { Class class = NSClassFromString(@"SecondViewController"); UIViewController *vc = class.new; if (aSelector == NSSelectorFromString(@"secondVCMethod")) { NSLog(@"secondVC do this !"); return vc; } return nil; } + (BOOL)resolveInstanceMethod:(SEL)sel { return [super resolveInstanceMethod:sel]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end
运行结果
**2015-12-24 14:00:34.168 RuntimeTest2[3284:870957] secondVC do this !** **2015-12-24 14:00:34.169 RuntimeTest2[3284:870957] This is secondVC method !**
咱们会发现- (void)secondVCMethod
这个方法执行了,程序也并无崩溃,缘由就是在这一步
- (id)forwardingTargetForSelector:(SEL)aSelector { Class class = NSClassFromString(@"SecondViewController"); UIViewController *vc = class.new; if (aSelector == NSSelectorFromString(@"secondVCMethod")) { NSLog(@"secondVC do this !"); return vc; } return nil; }
在没有找到- (void)secondVCMethod
这个方法的时候,消息继续传递,直到- (id)forwardingTargetForSelector:(SEL)aSelector
,而后我在里面建立了一个SecondViewController
的对象,而且判断如过有这个方法,就返回SecondViewController
的对象。这个函数就是消息的转发,在这儿咱们成功的把消息传给了SecondViewController
,而后让它来执行,因此就执行了那个方法。同时,也至关于完成了一个多继承!
固然,还有好几个函数,在上面那张图里面已经清晰的表达了,有兴趣的能够本身试试,看看消息的传递顺序究竟是怎么样的。上面提到的这些知识runtime
的冰山一角,runtime
黑魔法的强大远不止于此,好比方法的调配(Method Swizzling
)等,在项目实战中仍是颇有用的,后面有时间会再介绍.
参考