I want to use message forwarding in my SZNUnmanagedReference class. It has the following properties:
@property (nonatomic, strong) NSSet *authors;
@property (nonatomic, strong) SZNReferenceDescriptor *referenceDescriptor;
Basically, when an UnmanagedReference instance receives a message authorsString, it should forward it to referenceDescriptorthat which has a method with a name - (NSString *)authorsStringWithSet:(NSSet *)authors.
So, I wrote this in 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;
}
Everything works, the code in the class SZNReferenceDescriptoris executed. However, I do not know how to get it authorsStringback. If I understand the documentation correctly, I think I referenceDescriptorshould send the result back to the original sender of the message. But it does not seem to work. In my test class [unmanagedReference authorsString]returns nil.
source
share