本文介绍了Self = [超级初始化]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果 self 能够存储基类实例,那么当我们返回 self 时,它如何转换为派生实例.

If self is able to store the base class instance then when we are returning the self, how it transformed to derived instance.

推荐答案

这就是我认为您要问的问题:假设我们有一个基类 Base 和一个子类 Derived.如果 -[Derived init] 调用 -[Base init] 并且 -[Base init] 返回一个不同的实例,那个不同的实例不会是 Base 而不是 Derived 的实例,因此不合适?例如,新对象不会包含 Derived 可能已添加到类中的实例变量.

Here's what I think you're asking: suppose we have a base class Base and a subclass Derived. If -[Derived init] calls -[Base init] and -[Base init] returns a different instance, won't that different instance be an instance of Base and not Derived and thus inappropriate? For example, the new object won't have the instance variables that Derived might have added to the class.

答案是 Base 不允许这样做.如果它替换原始实例,它必须以尊重原始实例的动态类型的方式进行.例如,它可能会执行以下操作:

The answer is that Base is not allowed to do that. If it replaces the original instance, it must do so in a manner that respects the dynamic type of that original instance. For example, it might do something like:

// Re-allocate with 100 extra bytes
id newSelf = NSAllocateObject([self class], 100, [self zone]);
[self release];
self = newSelf;
// ... continue to initialize ...
return self;

或者,它可能会动态生成原始类的新子类,然后分配该新类的新实例.

Or, it might dynamically generate a new subclass of the original class and then allocate a new instance of that new class.

NSString* newClassName = [NSString stringWithFormat:"%@_DynamicSubclass", NSStringFromClass([self class])];
Class newClass = objc_allocateClassPair([self class], [newClassName UTF8String], 0);
// ... further configure the new class, by adding instance variables or methods ...
objc_registerClassPair(newClass);
id newSelf = [newClass alloc];
[self release];
self = newSelf;
// ... continue to initialize ...
return self;

无论做什么,它都必须满足新实例适合在旧实例所在的任何地方使用的约束,基于其动态类型.

Whatever it does, it has to satisfy the constraint that the new instance is suitable to be used wherever the old instance was, based on its dynamic type.

这篇关于Self = [超级初始化]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 09:24