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

问题描述:

我很困惑与[UIView的INIT]和[UIView的initWithFrame:方法XX],之后我搜索计算器,我发现下面的问题和答案:iOS:UIView子类init会调用[super init],然后调用超类中的方法,为什么它会调用[subclass initWithFrame:xx]?

Why do both init functions get called

iOS: UIView subclass init or initWithFrame:? 然后我konw的initwithFrame是设计初始值设定项,当我们调用[myview init](myView是UIView的子类并覆盖init和initwithfrme :)时,它会调用call [super init],然后它会调用[super initWithFrame:xx] as super会在超类中找到方法,为什么它会调用[myView initWithFrame:xx] ???

由于initWithFrame:是指定初始化,苹果的实施init(当你调用[super init]你打电话)在内部调用initWithFrame:功能并传递CGRectZero。这就是被召唤的原因。所以最终流最终看起来像这样:

[YourClass init] -> [super init] -> [self initWithFrame:CGRectZero] -> 
[YourClass initWithFrame:CGRectZero] -> [super initWithFrame:CGRectZero] 

这是假设你叫[super init]当你要替换init在YourClass和[super initWithFrame:]当你重写initWithFrame

+0

感谢您的帮助。我可以看到它。什么让我感到困惑是我在其他问题中发现我列出的答案是[YourClass init] - > [super init] - > [YourClass initWithFrame] - > [super initWithFrame:CGRectZero],它会调用子类的initWithFrame然后调用超类,这让我感到困惑?为什么要调用[YourClass initWithFrime:XX]? – Luca

+0

我更新了我的答案,真的会发生什么是[超级初始化]调用[self initWithFrame] ...这是什么触发[YourClass initwithFrame:],然后调用[super initWithFrame:] –

+0

是的,如果它是那么答案应该是。但为什么“[super init]调用[self initWithFrame]”,因为我们知道super是魔术字告诉编译器在超类中查找方法,所以应该“[super init]调用[super initWithFrame]”??? – Luca

它会调用调用[超级的init],然后它会调用[超级 initWithFrame:方法XX]超级会发现在超类的方法,它为什么 会调用[MyView的initWithFrame:方法XX] ???

不,没有这样的事情是supersuper只是一种语法,允许您使用不同的方法查找机制调用self上的方法。在这里,[super init]调用将查找在您的对象上调用的方法-[UIView init](指向的那个self)。在-[UIView init]里面,它有一个叫[self initWithFrame:],它再次在你的对象上被调用(一个self指向)。在这里它不使用super,所以使用常规方法查找机制(UIView的超类无论如何都没有-initWithFrame:)。常规方法查找机制在对象的类中找到最重写的实现。由于你的类(你的对象的类)重写-initWithFrame:,它查找的方法是-[YourClass initWithFrame:]

+0

谢谢。我想我在问题之前误解了超级关键字。现在我知道你和john_ryan的帮助 - > super只是一种语法,允许你使用不同的方法查找机制来调用自己的方法。 – Luca