0
我目前正試圖利用forwardInvocation
,但有一些麻煩。我想轉發ClassA
調用一個有限的方法集到作爲屬性存儲在我的ClassA
中的另一個實例(ClassB
),但是我也希望在我的ClassA
中有一個回退方法,如果方法未實現在ClassB
。forwardInvocation不轉發調用
不幸的是,我發現任何方法在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!
}
這就是答案。似乎回想起來很明顯。非常感謝! – majackson