美文网首页
runtime01-消息转发机制

runtime01-消息转发机制

作者: Leopard90 | 来源:发表于2021-11-25 16:02 被阅读0次

    以发送sendMessage:带参方法为例

    1、动态方法解析

     + (BOOL)resolveInstanceMethod:(SEL)sel{

        //动态方法解析

        NSString*methodName =NSStringFromSelector(sel);

        if([methodNameisEqualToString:@"sendMessage:"]) {

            class_addMethod(self, sel, (IMP)sendMessage,"v@:@");

        }

        return NO;

    }

    2、快速转发

     + (BOOL)resolveInstanceMethod:(SEL)sel

    {

        return NO;

    }

    backUpPerson是备份类方法

    - (id)forwardingTargetForSelector:(SEL)aSelector

    {

        //快速查找

            NSString*methodName =NSStringFromSelector(aSelector);

            if([methodName isEqualToString:@"sendMessage:"]) {

                return [backUpPerson new];

            }

        return [super forwardingTargetForSelector:aSelector];

    }

    3、慢速转发分两步 

        a、方法签名  b、消息转发

    + (BOOL)resolveInstanceMethod:(SEL)sel

    {

    return NO;

    }

    - (id)forwardingTargetForSelector:(SEL)aSelector

    {

            [super forwardingTargetForSelector:aSelector];

    }

    //方法签名

    - (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector

    {

        NSString*methodName =NSStringFromSelector(aSelector);

        if([methodName isEqualToString:@"sendMessage:"]) {

            return [NSMethodSignature signatureWithObjCTypes:"v@:@"];

        }

        return [super methodSignatureForSelector:aSelector];

    }

    //消息转发

    - (void)forwardInvocation:(NSInvocation*)anInvocation

    {

        SELsel = [anInvocation selector];

        backUpPerson *tempObj = [backUpPerson new];

        if([tempObj respondsToSelector:sel]) {

            [anInvocation invokeWithTarget:tempObj];

        }else{

            [super forwardInvocation:anInvocation];

        }

    }

    三者都找不到方法时,最后调用

    - (void)doesNotRecognizeSelector:(SEL)aSelector

    {

    NSLog(@"找不到方法");

    }

    相关文章

      网友评论

          本文标题:runtime01-消息转发机制

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