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