我目前正在尝试使用forwardInvocation
但遇到了一些麻烦。我想将ClassA
一组有限方法的调用转发到ClassB
存储为 my 中的属性的另一个实例 (of ) ClassA
,但我还希望在 my 中有一个后备方法ClassA
,如果方法未在ClassB
.
不幸的是,我发现无论在什么方法上实现ClassB
,ClassA
方法总是被调用!
我实现这一点的方式如下所示。任何人都可以就我哪里出错提供任何建议吗?
static NSSet *forwardMessages;
@implementation ClassA
@synthesize classBInstance;
- (id) initWithDelegate:(id)delegate {
self = [super init];
classBInstance = delegate;
return self;
}
+ (void) initialize {
if (self == [ClassA class]) {
forwardMessages = [[NSSet alloc] initWithObjects:
@"doSomething",
@"doSomethingElse",
@"anotherThing",
@"yetMoreThings",
nil];
- (BOOL) respondsToSelector:(SEL)aSelector {
return [super respondsToSelector:aSelector] || [self isHandledByDelegate:aSelector];
}
- (BOOL) isHandledByDelegate:(SEL)aSelector {
return [forwardMessages containsObject:NSStringFromSelector(aSelector)] &&
[classBInstance respondsToSelector:aSelector];
}
- (void)forwardInvocation:(NSInvocation *)anInvocation
{
BOOL forwardThis = [self isHandledByDelegate: [anInvocation selector]];
if (forwardThis) {
[anInvocation invokeWithTarget:classBInstance];
} else {
[super forwardInvocation:anInvocation];
}
}
- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector {
Class handlingClass = [self isHandledByDelegate:aSelector]? [classBInstance class]:[self class];
return [handlingClass instanceMethodSignatureForSelector:aSelector];
}
- (void) doSomething {
// this should be forwarded to classBInstance but is always called!
}