原文地址: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
)等,在項目實戰中仍是頗有用的,後面有時間會再介紹.
參考