美文网首页
消息转发封装

消息转发封装

作者: BabyNeedCare | 来源:发表于2023-06-02 22:17 被阅读0次

    .h

    
    @interface ForwardingProxy : NSProxy
    
    @property (nonatomic, strong) id target;
    - (instancetype)initWithTarget:(id)target;
    
    @end
    
    
    @interface TargetClass : NSObject
    
    - (void)existingMethod;
    - (void)anotherExistingMethod;
    
    @end
    
    
    #import "ForwardingProxy.h"
    
    @implementation ForwardingProxy
    
    - (instancetype)initWithTarget:(id)target {
        _target = target;
        return self;
    }
    
    - (BOOL)respondsToSelector:(SEL)aSelector {
        return [self.target respondsToSelector:aSelector];
    }
    
    - (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector {
        NSMethodSignature *methodSignature = [self.target methodSignatureForSelector:aSelector];
        if (methodSignature) {
            return methodSignature;
        }
        return [NSMethodSignature signatureWithObjCTypes:"v@:"];
    }
    
    - (void)forwardInvocation:(NSInvocation *)anInvocation {
        SEL selector = anInvocation.selector;
        if ([self.target respondsToSelector:selector]) {
            [anInvocation invokeWithTarget:self.target];
        } else {
            [self handleUnknownSelector:selector];
        }
    }
    
    - (void)handleUnknownSelector:(SEL)selector {
        NSLog(@"Unknown selector: %@", NSStringFromSelector(selector));
    }
    
    @end
    
    
    @implementation TargetClass
    
    - (void)existingMethod {
        NSLog(@"Existing method called");
    }
    @end
    
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        // Do any additional setup after loading the view.
    
        TargetClass *target = [[TargetClass alloc] init];
        ForwardingProxy *proxy = [[ForwardingProxy alloc] initWithTarget:target];
        
        [proxy performSelector:@selector(existingMethod)];
        
        [proxy performSelector:@selector(nonExistentMethod)];
        
        [proxy performSelector:@selector(anotherExistingMethod)];
    
    }
    
    
    

    打印结果:
    Invocation[3637:122461] Existing method called
    Invocation[3637:122461] Unknown selector: nonExistentMethod
    Invocation[3637:122461] Unknown selector: anotherExistingMethod

    - (void)viewDidLoad {
        [super viewDidLoad];
        // Do any additional setup after loading the view.
        id target = NSClassFromString(@"Worker");
        ForwardingProxy *proxy = [[ForwardingProxy alloc] initWithTarget:target];
        [proxy performSelector:@selector(existingMethod)];
        [proxy performSelector:@selector(anotherExistingMethod)];
        
    }
    

    相关文章

      网友评论

          本文标题:消息转发封装

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