O'Reilly logo

Objective-C Pocket Reference by Andrew Duncan

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required