software-mariodiana
1/27/2017 - 3:43 PM

Message forwarding requires overriding two methods of NSObject. Here, we imagine a class that wraps a UIControl object and takes a delegate.

Message forwarding requires overriding two methods of NSObject. Here, we imagine a class that wraps a UIControl object and takes a delegate. When given a message it doesn't respond to, the class first asks the delegate if it can handle it, and if it can't, it then asks the wrapped object (the UIControl) if it can handle the message.

- (void)forwardInvocation:(NSInvocation *)anInvocation
{
    if ([[self delegate] respondsToSelector:[anInvocation selector]])
    {
        [anInvocation invokeWithTarget:[self delegate]];
    }
    else if ([[self control] respondsToSelector:[anInvocation selector]])
    {
        [anInvocation invokeWithTarget:[self control]];
    }
    else
    {
        [super forwardInvocation:anInvocation];
    }
}


- (NSMethodSignature *)methodSignatureForSelector:(SEL)selector
{
    NSMethodSignature* signature = [super methodSignatureForSelector:selector];
    
    if (!signature)
    {
        signature = [[self delegate] methodSignatureForSelector:selector];
        
        if (!signature)
        {
            signature = [[self control] methodSignatureForSelector:selector];
        }
    }
    
    return signature;
}