Skip navigation.
 
mlRe: Forwarding messages from an application delegate
FROM : Graham Cox
DATE : Fri May 02 17:18:33 2008

On 3 May 2008, at 12:56 am, Matthew Gertner wrote:

> Seems like you can "pretend" you implement them using
> respondsToSelector (see Graham's reply).



Exactly - the delegate is sent the message if it says it implements 
it, even if it really doesn't. Then NSObject says "wait a minute, I 
don't implement that!" so it checks if -forwardInvocation: is 
implemented, and if so turns the message into an invocation and passes 
it to -forwardInvocation:, which can then pass it to the real object 
that does implement it. If -forwardInvocation: isn't implemented, it 
gives up by calling -doesNotRecognizeSelector:

It's a very neat mechanism.

And you can take it further: One use I've found for this is getting 
messages from first responder down to some more appropriate object 
deeper inside a complex hierarchy - the view (firstR) forwards 
anything it doesn't handle to its controller, which does the same to 
other objects it knows about, which do the same to things they 
contain... it makes it seem as if the view can magically handle all 
sorts of messages and actions but in reality they are implemented by 
the underlying objects that can implement the messages directly, 
including all the usual protocols such as e.g. NSMenuItemValidation. 
As the internal context changes, menu items magically enable/disable 
as appropriate, and yet the view needs to know nothing about what's 
going on underneath.

Coming from a C++ background, this sort of thing is what makes Obj-C 
so compelling.

G.

Related mailsAuthorDate
mlForwarding messages from an application delegate Matthew Gertner May 2, 16:35
mlRe: Forwarding messages from an application delegate Graham Cox May 2, 16:44
mlRe: Forwarding messages from an application delegate Andy Lee May 2, 16:53
mlRe: Forwarding messages from an application delegate Andy Lee May 2, 16:55
mlRe: Forwarding messages from an application delegate Matthew Gertner May 2, 16:55
mlRe: Forwarding messages from an application delegate Matthew Gertner May 2, 16:56
mlRe: Forwarding messages from an application delegate Bill Cheeseman May 2, 17:04
mlRe: Forwarding messages from an application delegate Graham Cox May 2, 17:18