.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)];
}
网友评论