Runtime消息转发及其应用

2018-11-02  本文已影响27人  Misaki_yuyi

  之前写过文章Runtime的常见用法里面有介绍过利用Objective-CRuntime特性来给Category生成属性、实现方法交换和给Model赋值。今天整理一下Objective-C消息传递和消息转发机制以及来防止应用闪退的问题。

消息传递

  打开#import<objc/runtime.h>文件,看到struct objc_class的定义

struct objc_class {
    Class _Nonnull isa  OBJC_ISA_AVAILABILITY;

#if !__OBJC2__
    Class _Nullable super_class                              OBJC2_UNAVAILABLE;
    const char * _Nonnull name                               OBJC2_UNAVAILABLE;
    long version                                             OBJC2_UNAVAILABLE;
    long info                                                OBJC2_UNAVAILABLE;
    long instance_size                                       OBJC2_UNAVAILABLE;
    struct objc_ivar_list * _Nullable ivars                  OBJC2_UNAVAILABLE;
    struct objc_method_list * _Nullable * _Nullable methodLists                    OBJC2_UNAVAILABLE;
    struct objc_cache * _Nonnull cache                       OBJC2_UNAVAILABLE;
    struct objc_protocol_list * _Nullable protocols          OBJC2_UNAVAILABLE;
#endif
} OBJC2_UNAVAILABLE;

  结构体中有很多变量,分别是父类的指针、类的名字、类的版本、实例大小、变量列表、方法列表、方法缓存、协议列表。一个类对象就是一个结构体struct objc_class ,这个结构体存放的数据称为metadata(元数据),结构体的第一个成员变量是一个isa指针,isa指针指向metaclass(元类)

  在看看Method

Method(objc_method)
struct objc_method {
    SEL _Nonnull method_name                                 OBJC2_UNAVAILABLE;
    char * _Nullable method_types                            OBJC2_UNAVAILABLE;
    IMP _Nonnull method_imp                                  OBJC2_UNAVAILABLE;
}    

  这个就是平常使用的函数,能够独立完成一个功能的一段代码

  一般OC中函数调用例如 [obj dosomthing]都会被编译器转义成objc_msgsend(obj,dosomething),obj就是对象实例,dosomethingSEL类型。Runtime的执行的流程是

消息转发

  发生消息转发,还有三次机会,假如都失败了就会执行doesNotRecognizeSelector:报错unrecognized selector

iOS 消息转发流程图.png

动态方法解析

[self performSelector:@selector(testMethod:) withObject:@"something"];

  我在ViewController里面调用testMethod方法,但是没有在ViewController申明这个方法,运行起来肯定是崩溃的。
在运行时,如果找不到要执行的方法,会首先执行resolveClassMethod:或者resolveInstanceMethod:

#pragma mark - 添加的IMP
void myMethod(id self, SEL cmd, id value)
{
    NSLog(@"%@",value);
}

#pragma mark - 找不到对象方法时候调用
+ (BOOL)resolveInstanceMethod:(SEL)sel
{
    if (sel == @selector(testMethod:))
    {
        class_addMethod([self class],sel,(IMP)myMethod,"v@:@");
        return YES;
    }
    else
    {
        return [super resolveInstanceMethod:sel];
    }
}

#pragma mark - 找不到类方法时调用
+ (BOOL)resolveClassMethod:(SEL)sel
{
    return [super resolveClassMethod:sel];
}

  当ViewController对象找不到testMethod方法,首先调用resolveInstanceMethod进行拦截补救。判断ViewController找不到的方法是否为testMethod
如果是testMethod,调用class_addMethodViewController动态的添加testMethod方法。
class_addMethod的四个参数分别是

备用接收者

  假如没有在resolveInstanceMethod里面动态添加方法,还是会崩溃,这个时候需要另外一个对象来接收这个消息。新建一个BackupViewController类,然后让BackupViewController去执行testMethod方法。

@implementation BackupViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)testMethod:(NSString *)str
{
    NSLog(@"%@",str);
}

@end
#pragma mark - 找不到对象方法时候调用
+ (BOOL)resolveInstanceMethod:(SEL)sel
{
    return [super resolveInstanceMethod:sel];
}

#pragma mark - 找不到类方法时调用
+ (BOOL)resolveClassMethod:(SEL)sel
{
    return [super resolveClassMethod:sel];
}

#pragma mark - 寻找备用接收者
- (id)forwardingTargetForSelector:(SEL)aSelector
{
    BackupViewController * backup = [[BackupViewController alloc] init];
    if ([backup respondsToSelector:@selector(testMethod:)])
    {
        return backup;
    }
    return [super forwardingTargetForSelector:aSelector];
}

  这个很好理解,既然自己不能动态添加方法,那就让其他的对象来接收这个消息,但是需要注意的是,这个备用者不能是self本身,否则会陷入循环中。

完整消息转发

  假如不动态添加方法,也不转发给备用接收者,这个时候就需要完整消息转发NSInvocation来处理。

#pragma mark - ViewController找不到方法的实现签名,需要给aSelector新建方法签名,在交给Backup处理
- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector
{
    NSMethodSignature * signature = [super methodSignatureForSelector:aSelector];
    if (!signature)
    {
        signature = [BackupViewController instanceMethodSignatureForSelector:aSelector];
    }
    return signature;
}

#pragma mark - 方法签名后进入forwardInvocation方法
- (void)forwardInvocation:(NSInvocation *)anInvocation
{
    SEL sel = anInvocation.selector;
    BackupViewController * backup = [[BackupViewController alloc] init];
    if ([backup respondsToSelector:sel])
    {
        [anInvocation invokeWithTarget:backup];
    }
    else
    {
        [self doesNotRecognizeSelector:sel];
    }
}

  首先创建NSInvocation对象,把尚未处理的那条消息有关的全部细节封装于这个NSInvocation对象中。此对象中包含选择子(selector)、目标(target)及参数。在触发NSInvocation对象时,会调用forwardInvocation来转发消息,如果发现调用操作不由本类来处理,则需要沿着继承体系,调用父类的同名方法,一直到NSObject类,调用doesNotRecognizeSelector来抛出异常,消息转发结束。

应用

  在这里消息转发三个步骤中,第一步resolveInstanceMethod可以解决问题,但是需要在当前对象添加不存在的方法。第三步,会导致消息流转的周期变长,还会产生NSInvocation,增加额外的开销。所以在应用中,在第二步处理消息防止应用闪退。
  可以动态的创建一个类,动态的给该类添加对应的Selector,通过一个通用的返回0的函数来实现改SELIMP。然后将消息转发到这个类上。

#import "ForwardingTarget.h"
#import <objc/runtime.h>

@implementation ForwardingTarget

id ForwardingTarget_dynamicMethod(id self, SEL _cmd)
{
    return [NSNull null];
}

+ (BOOL)resolveInstanceMethod:(SEL)sel
{
    class_addMethod([self class], sel, (IMP)ForwardingTarget_dynamicMethod, "@@:");
    return [super resolveInstanceMethod:sel];
}

- (id)forwardingTargetForSelector:(SEL)aSelector
{
    id result = [super forwardingTargetForSelector:aSelector];
    return result;
}

- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector
{
    id result = [super methodSignatureForSelector:aSelector];
    return result;
}

- (void)forwardInvocation:(NSInvocation *)anInvocation
{
    [super forwardInvocation:anInvocation];
}

- (void)doesNotRecognizeSelector:(SEL)aSelector
{
    [super doesNotRecognizeSelector:aSelector];
}

@end


#import "NSObject+DoesNotRecognizeSelectorExtension.h"

#import "ForwardingTarget.h"
#import <objc/runtime.h>

static ForwardingTarget * _target = nil;

@implementation NSObject (DoesNotRecognizeSelectorExtension)

+ (void)load
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _target = [ForwardingTarget new];;
        not_recognize_selector_classMethodSwizzle([self class], @selector(forwardingTargetForSelector:), @selector(doesnot_recognize_selector_swizzleForwardingTargetForSelector:));
    });
}


- (id)doesnot_recognize_selector_swizzleForwardingTargetForSelector:(SEL)aSelector
{
    id result = [self doesnot_recognize_selector_swizzleForwardingTargetForSelector:aSelector];
    if (result)
    {
        return result;
    }

    return _target;
}

#pragma mark - private method

BOOL not_recognize_selector_classMethodSwizzle(Class aClass, SEL originalSelector, SEL swizzleSelector)
{
    Method originalMethod = class_getInstanceMethod(aClass, originalSelector);
    Method swizzleMethod = class_getInstanceMethod(aClass, swizzleSelector);
    BOOL didAddMethod =
    class_addMethod(aClass,
                    originalSelector,
                    method_getImplementation(swizzleMethod),
                    method_getTypeEncoding(swizzleMethod));
    if (didAddMethod)
    {
        class_replaceMethod(aClass,
                            swizzleSelector,
                            method_getImplementation(originalMethod),
                            method_getTypeEncoding(originalMethod));
    }
    else
    {
        method_exchangeImplementations(originalMethod, swizzleMethod);
    }
    return YES;
}


@end

参考
iOS unrecognized selector crash 自修复技术实现与原理解析
大白健康系统--iOS APP运行时Crash自动修复系统

上一篇下一篇

猜你喜欢

热点阅读