关于Runtime的消息机制

一.关于runtime

关于runtime一直是开发者津津乐道的问题,之前项目中有个改变全局字体有用到过runtime,感受到了runtime黑魔法的强大,本文中简要谈谈我对runtime的一些理解。
对象调用方法是Objective-C的一大特色,其本质也就是消息的传递,而Objective-C是C的超集,所以和C不同的是,Objective-C使用的是动态运行时,也就是runtime。Objective-C的消息传递和消息机制也就不多说了,本人主要说的是动态方法的调用。

二.相关的几个函数

下面这张图详细的概括了每个函数调用的先后顺序以及执行的前提条件

关于Runtime的消息机制_第1张图片
消息传递函数的调用.png

1.对象在收到无法解读的消息后,首先会调用所属类的

+ (BOOL)resolveInstanceMethod:(SEL)sel

这个方法在运行时,没有找到SEL的IML时就会执行。这个函数是给类利用class_addMethod添加函数的机会。根据文档,如果实现了添加函数代码则返回YES,未实现返回NO。举个例子,新建了一个工程,首先我在ViewController这个类中执行doSomething1这个方法,
代码如下:

//
//  ViewController.m
//  RuntimeTest1
//
//  Created by 邓昊 on 2017/7/5.
//  Copyright © 2017年 HarrisDeng. 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

运行结果:

2017-07-05 17:57:09.855 RuntimeTest1[1353:136988] -[ViewController doSomething]: unrecognized selector sent to instance 0x7fe584e0c100
2017-07-05 17:57:09.867 RuntimeTest1[1353:136988] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[ViewController doSomething]: unrecognized selector sent to instance 0x7fe584e0c100'
*** First throw call stack:

不出意外,程序崩溃,因为没有找到doSomething这个方法,下面我们在里面实现 + (BOOL)resolveInstanceMethod:(SEL)sel这个方法,并且判断如果SEL 是doSomething那就输出add method here

//
//  ViewController.m
//  RuntimeTest1
//
//  Created by 邓昊 on 2017/7/5.
//  Copyright © 2017年 HarrisDeng. 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

2017-07-05 18:07:11.983 RuntimeTest1[1414:145616] add method here
2017-07-05 18:07:11.983 RuntimeTest1[1414:145616] -[ViewController doSomething]: unrecognized selector sent to instance 0x7fe31e5077a0
2017-07-05 18:07:11.987 RuntimeTest1[1414:145616] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[ViewController doSomething]: unrecognized selector sent to instance 0x7fe31e5077a0'
*** First throw call stack:

可以看到程序依然是崩溃了,但是我们可以看到输出了add method here,这说明我们 + (BOOL)resolveInstanceMethod:(SEL)sel这个方法执行了,并进入了判断,所以,在这儿,我们可以做一下操作,使这个方法得到相应,不至于走到最后- (void)doesNotRecognizeSelector:(SEL)aSelector这个方法中而崩掉了,接下来,继续操作,如下

//
//  ViewController.m
//  RuntimeTest1
//
//  Created by 邓昊 on 2017/7/5.
//  Copyright © 2017年 HarrisDeng. All rights reserved.
//

#import "ViewController.h"
#import   //注意导入

@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

导入了并且在+ (BOOL)resolveInstanceMethod:(SEL)sel中执行了class_addMethod这个方法,然后定义了一个void dynamicMethodIMP (id self, SEL _cmd)这个函数,运行工程,看log

2017-07-05 18:15:03.529 RuntimeTest1[1506:152724] add method here
2017-07-05 18:15:03.530 RuntimeTest1[1506:152724] 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 邓昊 on 2017/7/5.
//  Copyright © 2017年 HarrisDeng. 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.
}

@end

现在我想在ViewController中调用- (void)secondVCMethod这个方法,我们知道ViewController和SecondViewController并无继承关系,按照正常的步骤去做程序肯定会因为在ViewController找不到- (void)secondVCMethod这个方法而直接崩溃的

//
//  ViewController.m
//  RuntimeTest2
//
//  Created by 邓昊 on 2017/7/5.
//  Copyright © 2017年 HarrisDeng. All rights reserved.
//

#import "ViewController.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

运行结果:

2017-07-05 18:25:11.285 RuntimeTest2[1633:161836] -[ViewController secondVCMethod]: unrecognized selector sent to instance 0x7fb13cc074e0
2017-07-05 18:25:11.288 RuntimeTest2[1633:161836] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[ViewController secondVCMethod]: unrecognized selector sent to instance 0x7fb13cc074e0'
*** First throw call stack:

现在我们来处理一下这个消息,如下:

//
//  ViewController.m
//  RuntimeTest2
//
//  Created by 邓昊 on 2017/7/5.
//  Copyright © 2017年 HarrisDeng. All rights reserved.
//

#import "ViewController.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

运行结果:

2017-07-05 18:27:53.297 RuntimeTest2[1676:165025] secondVC do this !
2017-07-05 18:27:53.297 RuntimeTest2[1676:165025] 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)等,在项目实战中还是很有用的,后面有时间会再介绍.

参考
Objective-C Runtime Reference
Objective-C Runtime Programming Guide

你可能感兴趣的:(关于Runtime的消息机制)