Overridden by subclasses to forward messages to other objects.
- iOS 2.0+
- macOS 10.0+
- Mac Catalyst 13.0+Beta
- tvOS 9.0+
- watchOS 2.0+
- Objective-C Runtime
The invocation to forward.
When an object is sent a message for which it has no corresponding method, the runtime system gives the receiver an opportunity to delegate the message to another receiver. It delegates the message by creating an
NSInvocation object representing the message and sending the receiver a
forward message containing this
NSInvocation object as the argument. The receiver’s
forward method can then choose to forward the message to another object. (If that object can’t respond to the message either, it too will be given a chance to forward it.)
forward message thus allows an object to establish relationships with other objects that will, for certain messages, act on its behalf. The forwarding object is, in a sense, able to “inherit” some of the characteristics of the object it forwards the message to.
An implementation of the
forward method has two tasks:
To locate an object that can respond to the message encoded in
an. This object need not be the same for all messages.
To send the message to that object using
anwill hold the result, and the runtime system will extract and deliver this result to the original sender.
In the simple case, in which an object forwards messages to just one destination (such as the hypothetical
friend instance variable in the example below), a
forward method could be as simple as this:
The message that’s forwarded must have a fixed number of arguments; variable numbers of arguments (in the style of
printf()) are not supported.
The return value of the forwarded message is returned to the original sender. All types of return values can be delivered to the sender:
id types, structures, double-precision floating-point numbers.
Implementations of the
forward method can do more than just forward messages.
forward can, for example, be used to consolidate code that responds to a variety of different messages, thus avoiding the necessity of having to write a separate method for each selector. A
forward method might also involve several other objects in the response to a given message, rather than forward it to just one.
NSObject’s implementation of
forward simply invokes the
does method; it doesn’t forward any messages. Thus, if you choose not to implement
forward, sending unrecognized messages to objects will raise exceptions.