iOS:UIView子类init将调用[super init],然后调用超类中的方法,为什么它将调用[subclass initWithFrame:xx]?

iOS:UIView子类init将调用[super init],然后调用超类中的方法,为什么它将调用[subclass initWithFrame:xx]?,ios,objective-c,uiview,super,Ios,Objective C,Uiview,Super,在搜索stackoverflow后,我发现以下问题和答案,我对[UIView init]和[UIView initWithFrame:xx]感到困惑: 然后我知道initwithFrame是设计的初始值设定项,让我困惑的是当我们调用[myview init](myview是UIView的子类,覆盖init和initwithfrme:),它会调用[super init],然后它会调用[super initwithFrame:xx],因为super会在超类中找到方法,为什么它会调用[myView

在搜索stackoverflow后,我发现以下问题和答案,我对[UIView init]和[UIView initWithFrame:xx]感到困惑:


然后我知道initwithFrame是设计的初始值设定项,让我困惑的是当我们调用[myview init](myview是UIView的子类,覆盖init和initwithfrme:),它会调用[super init],然后它会调用[super initwithFrame:xx],因为super会在超类中找到方法,为什么它会调用[myView initWithFrame:xx]??

因为
initWithFrame:
是指定的初始值设定项,所以苹果公司实现了
init
(当你调用
[super init]
时调用它)在内部调用
initWithFrame:
函数并传入
CGRectZero
。这就是调用这两个函数的原因。因此,结束流最终如下所示:

[YourClass init] -> [super init] -> [self initWithFrame:CGRectZero] -> 
[YourClass initWithFrame:CGRectZero] -> [super initWithFrame:CGRectZero]
这是假设在类中重写init时调用
[super init]
,在重写
initWithFrame
时调用
[super initWithFrame:

它将调用call[super init],然后它将调用[super init] initWithFrame:xx]因为super会在super类中找到方法,为什么 将调用[myView initWithFrame:xx]


不。没有这样的事情,
super
super
只是一种语法,允许您使用不同的方法查找机制在
self
上调用方法。在这里,
[super init]
调用将查找对象上调用的方法
-[UIView init]
。在
-[UIView init]
内部,它有一个调用
[self initWithFrame:
,该调用再次在您的对象上被调用(self指向的对象)。这里它不使用
super
,因此使用了正常的方法查找机制(UIView的超类无论如何都没有
-initWithFrame:
)。正常的方法查找机制会在对象类中查找被重写最多的实现。由于您的类(对象的类)重写了
-initWithFrame:
,因此它查找的方法是
-[YourClass initWithFrame:]

谢谢你的帮助。我可以看到它。让我困惑的是,我在列出的其他问题中发现,答案是[YourClass init]->[super init]->[YourClass initWithFrame]->[super initWithFrame:CGRectZero],它会调用子类的initWithFrame,然后调用超级类的,这让我困惑?为什么调用[YourClass initWithFrime:XX]?我更新了我的答案,真正发生的是[super init]调用[self initWithFrame]…这就是触发[YourClass initWithFrame:]的原因,然后反过来调用[super initWithFrame:]是的,如果是,那么答案应该是。但是为什么“[super init]调用[self initWithFrame]”正如我们所知,super是一个神奇的词,它告诉编译器在super类中查找方法,所以“[super init]应该调用[super initWithFrame]”?这就是苹果实现它的方式。[UIView init]的基本实现调用[UIView initWithFrame:CGRectZero]。我们不清楚苹果为什么做出这个决定,但它可能会简化他们的代码,并为UIView提供一个方便的初始值设定项。这是预期的行为。好的,我终于明白了。非常感谢。在[super init]之后的序列是[self initWithFrame:xx];谢谢。我想我误解了问题之前的关键字super。现在我知道了,在您和john_ryan的帮助下-->super只是一种语法,允许您使用不同的方法查找机制自行调用方法。