runtime那些事(訊息機制)

weixin_33809981發表於2018-01-23

一、關於runtime


之前在專案中有遇到過用runtime解決改變全域性字型的問題,所以再一次感受到了runtime黑魔法的強大,趁現在有機會分享一下對runtime的一些理解。 在物件呼叫方法是Objective-C中經常使用的功能,也就是訊息的傳遞,而Objective-CC的超集,所以和C不同的是,Objective-C使用的是動態繫結,也就是runtimeObjective-C的訊息傳遞和訊息機制也就不多說了,今天主要說的是動態方法,也就是函式的呼叫。

二、相關的幾個函式


下面一張圖詳細的概括了每個函式呼叫的先後以及執行的前提

  • 1.物件在收到無法解讀的訊息後,首先會呼叫所屬類的 ***objc

+ (BOOL)resolveInstanceMethod:(SEL)sel

這個方法在執行時,沒有找到SELIMP時就會執行。這個函式是給類利用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`
複製程式碼

// //  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

**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這個方法中而崩掉了,接下來,我們繼續操作,如下

//
//  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

**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@:@");

  • 2.如果在+ (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這個方法,我們知道ViewControllerSecondViewController並無繼承關係,按照正常的步驟去做程式肯定會因為在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)等,在專案實戰中還是很有用的,後面有時間會再介紹.

參考

相關文章