我想在我的 SZNUnmanagedReference 类上使用消息转发。它具有以下属性:
@property (nonatomic, strong) NSSet *authors;
@property (nonatomic, strong) SZNReferenceDescriptor *referenceDescriptor;
基本上,当 UnmanagedReference 的实例接收到消息authorsString
时,它应该将其转发给referenceDescriptor
具有名为 的方法- (NSString *)authorsStringWithSet:(NSSet *)authors
。
所以,我写了这个SZNUnmanagedReference.m
:
- (void)forwardInvocation:(NSInvocation *)anInvocation {
SEL aSelector = anInvocation.selector;
if ([NSStringFromSelector(aSelector) isEqualToString:NSStringFromSelector(@selector(authorsString))]) {
NSMethodSignature *signature = [self.referenceDescriptor methodSignatureForSelector:@selector(authorsStringWithSet:)];
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
NSSet *authors = [NSSet setWithSet:self.authors];
[invocation setSelector:@selector(authorsStringWithSet:)];
[invocation setArgument:&authors atIndex:2];
[invocation setTarget:self.referenceDescriptor];
[invocation invoke];
} else {
[self doesNotRecognizeSelector:aSelector];
}
}
- (BOOL)respondsToSelector:(SEL)aSelector {
if ([super respondsToSelector:aSelector]) {
return YES;
} else if ([NSStringFromSelector(aSelector) isEqualToString:NSStringFromSelector(@selector(authorsString))] && [self.referenceDescriptor respondsToSelector:@selector(authorsStringWithSet:)]) {
return YES;
} else {
return NO;
}
}
- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector {
NSMethodSignature *signature = [super methodSignatureForSelector:aSelector];
if (!signature) {
signature = [self.referenceDescriptor methodSignatureForSelector:@selector(authorsStringWithSet:)];
}
return signature;
}
这一切似乎都有效,SZNReferenceDescriptor
类中的代码被执行。但是,我不知道如何authorsString
返回。如果我正确理解了文档,我认为referenceDescriptor
应该将结果发送回消息的原始发件人。但这似乎不起作用。在我的测试课中,[unmanagedReference authorsString]
返回nil
.