Objective c 编译时静态超绑定?
我想用一个基类和两个子类创建一个类集群。创建基类的实例应该根据某些条件返回子类,但是直接创建子类应该创建它。我在基类中编写了以下代码:Objective c 编译时静态超绑定?,objective-c,Objective C,我想用一个基类和两个子类创建一个类集群。创建基类的实例应该根据某些条件返回子类,但是直接创建子类应该创建它。我在基类中编写了以下代码: + (id)allocWithZone:(NSZone *)zone { // prevent infinite recursion if ([self isEqual:Base.class]) { // if self is the base class, return a correct subclass if
+ (id)allocWithZone:(NSZone *)zone {
// prevent infinite recursion
if ([self isEqual:Base.class]) {
// if self is the base class, return a correct subclass
if (somecondition) {
return [SubclassA alloc];
}
return [SubclassB alloc];
}
// otherwise, alloc is called on a subclass
// call NSObject's alloc
return [super allocWithZone:zone];
}
它是有效的,但我真的很惊讶它能起作用。也就是说,当在子类上调用时,为什么super会计算基类的超类(NSObject),而不是基类(因为在子类上调用时,超类是基类)?这就好像从Base继承的allocWithZone:method调用总是相对于Base进行超级计算,而不是调用方的实际运行时类。我认为Java和其他OO语言中类似的代码将无法工作,并导致无限递归,是吗?此代码是否错误?您的代码是正确的<代码>[super…]始终使用实现该方法的类的超类。在您的代码中,
+allocWithZone:
是由类Base
实现的,因此[super allocWithZone:zone]
在搜索下一个要调用的+allocWithZone:
实现时使用Base
的超类。是否有文档记录?我试着在clang文档中查找一下,但没有找到它。