Question

I‘ve read Apple's message forwarding document and other articles, and it seems the ObjC runtime will forward unrecognized messages for an object automatically, and if there isn't a matching selector, it will throw an "unrecognized selector sent to instance" error.

But I have two questions I can't explain.

  • How does the runtime find the next message forwarding object?
  • Can anyone explain the ObjC message forwarding chain?
Was it helpful?

Solution

and it seems the ObjC runtime will forward unrecognized messages for an object automatically

You've misunderstood. The runtime doesn't find the "next" object, it calls the same object's forwardInvocation: method. You can implement that method in your class if you want an object to forward certain messages to some other object, such as a delegate.

Can anyone explain the ObjC message forwarding chain?

You might be confusing message forwarding and the responder chain. The two aren't related. Cocoa and Cocoa Touch both include a 'responder' class (NSResponder and UIResponder respectively) that creates a "chain" of objects starting from the "first responder." Responders pass messages that they don't implement on to the next responder in the chain. For example, menu commands in Cocoa often send their action messages to the first responder, which might be something like a text field or other UI element. If that object doesn't handle the action, it passes it on to the next responder, and so on until the message either is handled by some object, or it reaches the end of the chain (the application object).

OTHER TIPS

Consider you have an object obj. In runtime if message call happens to obj, your SDK calls

methodSignatureForSelector:

of your object(since any class inherited from NSObject methodSignatureForSelector:

is available for all object). If it returns NSMethodSignature object then your obj has implemented the selector if it is nil your SDK would make your app crash.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top