Objective-C uses dynamic binding, but how?

后端 未结 2 684
终归单人心
终归单人心 2020-12-29 16:36

I know that Objective-C uses dynamic binding for all method calls. How is this implemented? Does objective-c \"turn into C code\" before compilation and just use (void*) p

2条回答
  •  天命终不由人
    2020-12-29 17:26

    Conceptually, what is going on is that there is a dispatcher library (commonly referred to as the Objective C runtime), and the compiler converts something like this:

    [myObject myMethodWithArg:a andArg:b ];
    

    into

    //Not exactly correct, but close enough for this
    objc_msgSend(myObject, "myMethodWithArg:andArg:", a, b);
    

    And then the runtime deals with all the binding and dispatch, finds an appropriate function, and calls it with those args. Simplistically you can think of it sort of like a hash lookup; of course it is much more complicated that then in reality.

    There are a lot more issues related to things like method signatures (C does not encode types so the runtime needs to deal with it).

提交回复
热议问题