iOS: UIView subclass init会调用[super init]然后调用superclass中的方法,为什么会调用[subclassinitWithFrame:xx]?

iOS: UIView subclass init will call [super init] then call methods in super class, why it will call [subclass initWithFrame:xx]?

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

Why do both init functions get called

iOS: UIView subclass init or initWithFrame:? 然后我知道 initwithFrame 是设计的初始化程序,让我对答案感到困惑的是当我们调用 [myview init](myView 是 UIView 的 subclass 并覆盖 init 和 initwithfrme:),它会调用 call [super init] 然后它会调用 [super initWithFrame:xx] 因为 super 会在 super class 中找到方法,为什么它会调用 [myView initWithFrame:xx]???

由于initWithFrame:是指定初始化器,apple实现init(调用[super init]时调用)内部调用initWithFrame:函数,传入CGRectZero。这就是两者都被调用的原因。所以最终流程最终看起来像这样:

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

假设您在 YourClass 中覆盖 init 时调用 [super init],在覆盖 initWithFrame 时调用 [super initWithFrame:]

it will call call [super init] then it will call [super initWithFrame:xx] as super will find methods in super class, why it will call [myView initWithFrame:xx]???

没有。没有这样的东西是supersuper 只是一种允许您使用不同的方法查找机制调用 self 上的方法的语法。在这里,[super init] 调用将查找在您的对象上调用的方法 -[UIView init]self 指向的方法)。在 -[UIView init] 中,它有一个调用 [self initWithFrame:],再次调用您的对象(self 指向的对象)。这里并没有使用super,所以使用了正常的方法查找机制(UIView的superclass反正是没有-initWithFrame:的。普通方法查找机制会在对象的 class 中找到最重写的实现。由于您的 class(对象的 class)覆盖了 -initWithFrame:,它查找的方法是 -[YourClass initWithFrame:].