Forwarding Messages

When an object is sent a message for which it has no method, the runtime system gives it another chance to handle the call before giving up. If the object supports a -forward :: method, the runtime calls this method, passing it information about the unhandled call. The return value from the forwarded call is propagated back to the original caller of the method.

Both Object and NSObject provide a -forward:: method, so all objects you are likely to encounter will behave as described in this section. In each case, the default behavior, implemented by the root class method, is to exit the program when an unhandled call is forwarded. Your classes can override this method to provide alternative behavior; common choices are to absorb the error or to redirect (forward) the unhandled message to another object, which is called a delegate .

Object Forwarding

The -forward:: method takes a selector and a second parameter that stores information about the parameters passed to the original (failed) method call.

The method supplied by GNU’s Object sets off the following train of events:

  1. -forward:: calls -doesNotRecognize : on self, passing the selector for the original method call.

  2. -doesNotRecognize: in turn calls -error : passing a format string and the name of the original method call.

  3. -error: logs an error message and aborts the program, unless you have overridden this method or installed an alternative error handler. Section 1.8 discusses this more.

If you want to just ignore messages ...

Get Objective-C Pocket Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.