Still confused about Objective-C's dynamic binding

家住魔仙堡 提交于 2019-12-13 14:12:40

问题


The question is from a comment I just added to the answer to this question, but it shouldn't be a duplicate.

The answer from @Bavarious to that question makes sense to me, but I am still confused why the runtime can not bind the method to the right object even the object is an id? to my understanding, dynamic binding or dynamic typing is that the compiler has no way of knowing what object behind an id, but the runtime is supposed to know that and choose the right object as the receiver of the message. but why the runtime can't do that?


回答1:


Short answer: C.

Expansion: When the compiler generates a call to a method, it is really just generating a call to a C function -- to objc_msgSend() or variant therein -- that dynamically binds and dispatches the method.

Because the C ABI runs "at the metal" (pretty close), the way that arguments and return values are passed can change dramatically based on the type. For example, the compiler can pass anything up to 32 bits in size in a register (or 64 bits in some architectures), but anything larger will be on the stack itself.

Because of this, the compiler can't necessarily emit a generic bit of assembly to call objc_msgSend() -- to dispatch the method call -- through (id) as the different signatures -- the different argument types to the method -- may require different code generation.

Now, technically, the compiler could generate the same code for many cases, but it chooses to take a conservative policy and complain. In particular, the assumption is that if you have 2 conflicting typed declarations, there may be others and reminding you that having a method of the same name with different argument types is extremely strongly discouraged.



来源:https://stackoverflow.com/questions/9460444/still-confused-about-objective-cs-dynamic-binding

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!