仍然对Objective-C的动态绑定感到困惑 [英] Still confused about Objective-C's dynamic binding

查看:102
本文介绍了仍然对Objective-C的动态绑定感到困惑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题来自我刚刚添加到的答案中的评论这个问题,但不能重复.

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

从@Bavarious到该问题的答案对我来说很有意义,但是我仍然感到困惑,为什么即使对象是id,运行时也无法将方法绑定到正确的对象?据我了解,dynamic bindingdynamic typing是编译器无法知道id后面的对象,但是运行时应该知道并且选择正确的对象作为消息的接收者.但是为什么运行时无法做到这一点?

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?

推荐答案

简短答案:C.

扩展:当编译器生成对方法的调用时,它实际上只是对C函数(对objc_msgSend()或其中的变体)的调用,它动态地绑定并分派该方法.

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.

由于C ABI是从头开始"运行的(非常接近),因此传递参数和返回值的方式可能会根据类型而发生巨大变化.例如,编译器可以在寄存器中传递最大为32位(在某些体系结构中为64位)的任何东西,但是任何更大的东西都将在堆栈本身上.

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.

因此,编译器不一定会发出通用的汇编位来调用objc_msgSend()-通过(id)作为不同的签名来分派方法调用—将不同的参数类型分配给该方法-可能需要不同的代码生成.

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.

这篇关于仍然对Objective-C的动态绑定感到困惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆