美文网首页
Runtime消息分发函数使用(四)

Runtime消息分发函数使用(四)

作者: wemt | 来源:发表于2018-05-13 11:47 被阅读0次

    在上一节消息分发中,使用到了NSMethodSignature和NSInvocation。这一节来看下这两者是干什么用的,如何来使用。

    NSMethodSignature

    从名字上来看,知道这是一个方法的签名。那么什么是方法签名,签名这两个字怎么理解呢?
    签名实际上就是指对方法的参数和返回值的类型的编码。那么类型的编码又是怎么样的?

    //@encode()能够取到类型的编码。
    char* intType = @encode(int);  //intType 的值为i。
    char* idType = @encode(id);    //idType的值为@。
    char* doubleType = @encode(double);//doubleType的返回值为d
    

    其他更多类型可以参考:Type Encode

    那么一个方法的签名是如何生成的呢,这里举一个实际的例子:

    - (void)testSignature:(NSString *)strPara withTwoPara:(NSArray *)arrStr
    {
        NSMethodSignature *signature = [self methodSignatureForSelector:_cmd]; //_cmd代表当前的方法,即@selector(testSignature:withTwoPara:)
        NSMethodSignature *manualSignature = [NSMethodSignature signatureWithObjCTypes:"v@:@@"];
        if ([signature isEqual:manualSignature]){
            NSLog(@"两个Signature是一样的。");   //会被执行
        }
    }
    

    字符串"v@:@@"代表方法的返回值和参数。返回值void的编码v放在最前面,现在假设其为第零个参数。第一个和第二个参数分别是self和_cmd的的编码。对于OC方法来说,这两个参数是固定的。从三个开始才是真正的参数。参数顺序按照从左到右排列。
    然后再来看下NSMethodSignature的定义:

    @interface NSMethodSignature : NSObject {
    @private
        void *_private;
        void *_reserved[5];
        unsigned long _flags;
    }
    
    + (nullable NSMethodSignature *)signatureWithObjCTypes:(const char *)types;
    
    @property (readonly) NSUInteger numberOfArguments;//参数个数
    - (const char *)getArgumentTypeAtIndex:(NSUInteger)idx NS_RETURNS_INNER_POINTER;//对应位置的参数类型。
    
    @property (readonly) NSUInteger frameLength;
    
    - (BOOL)isOneway;
    
    @property (readonly) const char *methodReturnType NS_RETURNS_INNER_POINTER;//返回值类型
    @property (readonly) NSUInteger methodReturnLength;//返回值长度
    
    @end
    

    实际使用到的也只有使用signatureWithObjCType生成一个签名。或者通过签名来获取参数的类型或者返回值的类型。所以可以把NSMethodSignature看成一个模型,仅仅只是用来存取方法相关的参数信息。

    NSInvocation

    这个类主要是负责方法调用相关。oc中的方法调用分成3种形式:

    //需要调用的方法
    - (NSString *)methodInvoke:(NSString *)paraOne withName:(NSString *)paraTwo
    {
        NSLog(@"paraOne:%@ paraTwo:%@ ",paraOne,paraTwo);
        return [NSString stringWithFormat:@"%@,%@",paraOne,paraTwo];
    }
    
    
    - (void)testInvocation
    {
        //1.正常调用
        [self methodInvoke:@"参数一" withName:@"参数二" ];
        //2.使用performSelector:系列方法调用。
        [self performSelector:@selector(methodInvoke:withName:) withObject:@"参数一" withObject:@"参数二" ];//最多两个
        //3.使用NSInvocation调用
        NSMethodSignature *signature = [self methodSignatureForSelector:@selector(methodInvoke:withName:)];
        NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
        [invocation setTarget:self];
        [invocation setSelector:@selector(methodInvoke:withName:)];
        NSString *paraOne = @"参数一";
        NSString *paraTwo = @"参数二";
        
        [invocation setArgument:&paraOne atIndex:2];//注意,是从2开始。不需要算入返回值
        [invocation setArgument:&paraTwo atIndex:3];
        [invocation invoke];
        void *result;
        [invocation getReturnValue:&result];//实际是给result进行初始化
        NSString *retStr = (__bridge NSString *)result;  //如果是alloc生成的返回值,需要注意一下内存管理。
        NSLog(@"返回值为:%@",retStr);
    }
    

    三种调用方式都是一样的。但是效率会有一些差别,方式一最快,方式二其次,方式三最慢。既然方式三NSInvocation用起来又麻烦,效率又最低,那干嘛还要使用。
    其实NSInvocation可以在和其他语言进行交互中使用。例如在JSPatch中,如果想要通过JavaScript调用OC,就会用到NSInvocation。NSInvocation提供了一种在运行时才决定调用具体方法的能力。performSelector也提供同样的能力,但是它限制住了参数个数。最多只能够传递2个参数,所以为了能够进行通用的方法调用只能够使用NSInvocation。

    再来看一下NSInvocation的定义:

    NS_SWIFT_UNAVAILABLE("NSInvocation and related APIs not available")
    @interface NSInvocation : NSObject {
    @private
        void *_frame;
        void *_retdata;
        id _signature;
        id _container;
        uint8_t _retainedArgs;
        uint8_t _reserved[15];
    }
    
    + (NSInvocation *)invocationWithMethodSignature:(NSMethodSignature *)sig;
    
    @property (readonly, retain) NSMethodSignature *methodSignature;
    
    - (void)retainArguments;
    @property (readonly) BOOL argumentsRetained;
    
    @property (nullable, assign) id target;
    @property SEL selector;
    
    - (void)getReturnValue:(void *)retLoc;
    - (void)setReturnValue:(void *)retLoc;
    
    - (void)getArgument:(void *)argumentLocation atIndex:(NSInteger)idx;
    - (void)setArgument:(void *)argumentLocation atIndex:(NSInteger)idx;
    
    - (void)invoke;
    - (void)invokeWithTarget:(id)target;
    
    @end
    

    从定义中也可以看出来,其提供的方法大部分也都在前面的示例中用到了。其主要提供的能力就是动态的去调用任意的OC的方法。特别注意一下(void)setReturnValue:(void*)retLoc这个方法,它能够将retLoc设置到方法调用的返回值的位置。也就是说,即使不执行[invocation invoke];也能获得返回值。因此可以将任意原有的方法替换成新的方法。利用这一点和前面的消息分发流程,就可以实现热修复了。

    //一个热修复的过程和方法替换的过程是差不多的。具体都是分成以下4步:
    
    //1.hook住原有方法。
    //2.取出原有方法的参数。
    //3.将参数交由给新方法(一般是JS方法或其他动态语言生成的方法)执行,并获取结果。
    //4.将结果填入到原有方法的返回值地址中。
    - (void)setReturnValue:(void *)retLoc;
    

    对于第四步,将结果填入到原有方法的返回值地址中,如果不通过NSInvocation的话,那就只能自己写汇编来实现了。

    参考:

    相关文章

      网友评论

          本文标题:Runtime消息分发函数使用(四)

          本文链接:https://www.haomeiwen.com/subject/xrsxrftx.html