2016-05-31 58 views
1

我很困惑與[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] ???

回答

3

由於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

0

它會調用調用[超級的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

相關問題