我在各处都看到Objective-C具有真正的动态绑定,而C++只有后期绑定。不幸的是,没有一本书清楚地解释它或讨论其基础实现。例如,C++使用虚表。Objective-C呢?
http://www.gnu.org/software/gnustep/resources/ObjCFun.html有一个相当不错的描述。
基本上,动态绑定意味着在实际进行方法调用时,会决定要调用哪个方法。如果您愿意,方法可以在那个时间点上动态选择。
编辑: 这是我了解到的更多细节。我不能保证它完全正确,但应该大部分正确。Objective C中的每个对象都是一个结构体,其第一个成员名为isa
,是一个指向类的指针。每个类本身也是一个对象,通常被布置为:
struct objc_class {
Class isa;
Class super_class;
const char *name;
long version;
long info;
long instance_size;
struct objc_ivar_list *ivars;
struct objc_method_list **methodLists;
struct objc_cache *cache;
struct objc_protocol_list *protocols;
};
在运行时,以下是方法查找的伪代码:
Follow isa to find the class
if implementation = class.lookup_method(method):
call implementation
else if get_implementation = class.lookup_method(forwardInvocation):
implementation = get_implementation(method)
if implementation:
call implementation
else:
raise runtime error
else:
raise runtime error
< p>那么这个lookup_method
是如何工作的呢?< /p>
def lookup_method (class, method):
if method in class.objc_cache:
return implementation from objc_cache
else if method in class.objc_method_list:
cache implementation from objc_method_list
return implementation
else if implementation = class.super_class.lookup_method(method):
cache implementation
return implementation
else:
return null
forwardInvocation
使未识别的方法转到您在变量中拥有的对象。这种委托可以在不知道该对象在运行时将是什么类型或支持哪些方法的情况下完成。您还可以向类添加方法 - 即使在运行时也可以 - 而无需访问源代码。您还可以对类和方法进行丰富的运行时内省。动态绑定和晚期绑定实际上是相同的。如果我们使用静态绑定或早期绑定,它会在编译时检查发生的问题(有关变量、表达式等的错误),并将这些信息存储在虚拟方法表中。晚期绑定只是将方法与虚拟方法表中的方法绑定。