Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does forwardInvocation: get called?

Looking only at the Objective-C runtime library, when a message is sent to an object that doesn't respond to it, the runtime system gives the receiver another chance to handle the message. So, the receiver's forward:: method, if implemented, gets called. However, looking at NSObject.mm, NSObject doesn't seem to implement forward::.

So, how does NSObject's forwardInvocation: method gets called, since the only thing the runtime system calls when a forwarding is needed is forward::? Does Foundation use objc_setForwardHandler (runtime.h) to set a new handler that calls forwardInvocation: whenever a message sent to a NSObject object needs to be forwarded?

like image 750
LuisABOL Avatar asked Mar 02 '13 19:03

LuisABOL


1 Answers

At some point way back in time, there was no NSObject in the Objective-C runtime. When the language was first created by Brad Cox and Tom Love they added in a root object class, called Object. This implemented [Object forward::] , which was used to do message forwarding.

A few years later, NextStep came along and made their own additions to the language, creating the OpenStep framework (which became Cocoa). NextStep got rid of the Object class, and replaced it with NSObject. One of the changes that was made was to replace the forward:: method with forwardInvocation. The Object class is still kicking around in the source code (as you have found), but I'm pretty sure it's not available in either iOS or 64 bit OS X apps.

You are correct to suggest that objc_setForwardHandler is used to indicate that forwardInvocation should be used instead of forward:: for all NSObjects. I am afraid I'm not sure when Foundation calls this...I would guess at NSObject initialisation. I am also not massively up on the underlying runtime implementation, but hopefully that will have been of at least some help?

like image 100
lxt Avatar answered Oct 04 '22 19:10

lxt