美文网首页
Runtime-消息转发 Method Swizzling

Runtime-消息转发 Method Swizzling

作者: UILabelkell | 来源:发表于2019-09-29 16:40 被阅读0次

    消息转发机制共分为3大步骤:

    1.Method resolution 方法解析处理阶段

    2.Fast forwarding 快速转发阶段

    3.Normal forwarding 常规转发阶段

    image.png

    消息转发机制

    动态方法解析

    #import <Foundation/Foundation.h>
    #import <objc/runtime.h>
    NS_ASSUME_NONNULL_BEGIN
    
    @interface Presson : NSObject
    
    -(void)sendMessage:(NSString *)message;
    
    @end
    
    #import "Presson.h"
    
    @implementation Presson
    
    void sendMessage(id self, SEL _cmd, NSString *msg){
        NSLog(@"----%@",msg);
    }
    
    + (BOOL)resolveInstanceMethod:(SEL)sel
    {
        // 1配置方法
        NSString *methodNme = NSStringFromSelector(sel);
        if ([methodNme isEqualToString:@"sendMessage:"]) {
            return  class_addMethod(self, sel, (IMP)sendMessage, "v@:@");
        }
        return NO;
    }
    
    @end
    
    #import "ViewController.h"
    #import "Presson.h"
    
    @interface ViewController ()
    
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
    
        [[Presson new]sendMessage:@"helloworld"];
    }
    
    
    @end
    

    快速转发

    //快速转发

    //-(id)forwardingTargetForSelector:(SEL)aSelector{
    //    // 1配置方法
    //    NSString *methodNme = NSStringFromSelector(aSelector);
    //    if ([methodNme isEqualToString:@"sendMessage:"]) {
    //        return  [SpareWheel new];
    //    }
    //    return [super forwardingTargetForSelector:aSelector];
    //}
    

    慢速转发

    //1.方法签名
    //2.消息转发
    -(NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector{
        NSString *methodNme = NSStringFromSelector(aSelector);
        if ([methodNme isEqualToString:@"sendMessage:"]) {
            return  [NSMethodSignature signatureWithObjCTypes:"v@:@"];
        }
        return [super forwardingTargetForSelector:aSelector];
    }
    
    -(void)forwardInvocation:(NSInvocation *)anInvocation{
    //    SEL sel = [anInvocation selector];
    //    SpareWheel *tempObj = [SpareWheel new];
    //    if ([tempObj respondsToSelector:sel]) {
    //        [anInvocation invokeWithTarget:tempObj];
    //    }else{
    //        [super forwardInvocation:anInvocation];
    //    }
        [super forwardInvocation:anInvocation];
    }
    
    -(void)doesNotRecognizeSelector:(SEL)aSelector
    {
        NSLog(@"找不到方法");
    }
    

    相关文章

      网友评论

          本文标题:Runtime-消息转发 Method Swizzling

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