Forwarding Messages in Objective-C

Can someone give a brief explanation of how to use message forwarding?

References

  • Apple Documentation: Apple documentation is generally good as a reference, but long enough to not be the best as an introduction.
+4
source share
2 answers

Simple delegation pattern: your object responds to the aMethod message, then it checks to see if any other object responds to the aMethod message by sending [otherObject replysToSelector: @selector (aMethod)], which returns bool. If otherObject does, everything is clear to you to send the message.

More technical quality factor NSInvocation method: if your object sent a message to which it cannot respond (crazyMethodName), then forwardInvocation is called on your object. By default, the implementation of forwardInvocation for NSObject simply calls doesNotRecognizeSelector, because, well, your object does not recognize the selector. You can override the default implementation of forwardInvocation by checking if another object is responding to the call selector, and calling this call on another object, if so.

+5
source

The usual use of message forwarding is to make the class act as a proxy for other classes: you send the message to an instance of this subclass of NSProxy and sends it depending on which class or object it considers necessary.

Forwarding messages does allow the class to receive messages that it is not intended to be accepted: you can even use it to dynamically create methods on the fly. An application of this is the NSManagedObject category, which allows you to access Core Data properties in method calls without subclassing NSManagedObject for each object. This reminds me of method_missing in Ruby.

+3
source

All Articles