[英]Difference between self and super
剛剛有一個菜鳥問題。 我試圖了解調用self和super之間的區別。 現在,我了解了繼承和其他基本的OOP概念,但是對我而言,自我和超級的概念仍然不清楚。 我將通過一個例子來說明我的問題。
因此,當手機上下顛倒傾斜時,以下代碼將執行鎖定。 我知道“ Scene2ViewController”是“ UIViewController”的子類,因此“ Scene2ViewController”繼承了UIViewController的所有方法。 因此,下面我以消息的接收者為self的方式調用performPergueWithIdentifier方法。 現在,當我將“自我”更改為“超級”時,代碼仍以相同的方式執行。 叫super和叫self不一樣嗎? 如果有人可以向我解釋這一點,將不勝感激。
//Scene2ViewController.m
- (BOOL)shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation)interfaceOrientation
{
if (interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown) {
[self performSegueWithIdentifier:@"SegueToScene1" sender:self];
}
return (interfaceOrientation ==
UIInterfaceOrientationPortrait);
}
self
和super
實際上都指向同一個對象。 super
是一個關鍵字,它告訴編譯器生成指令,這些指令開始在super類而不是當前類中搜索方法定義。
@interface A : NSObject {}
- (void)foo;
@end
@implementation A
- (void)foo {
NSLog(@"A's foo!");
}
@end
@interface B : A
@end
@implementation B
- (void)foo {
NSLog(@"B's foo!");
}
@end
//...somewhere in a method of class B...
[self foo]; // prints "B's foo" in the console
[super foo]; // prints "A's foo" in the console
如果我們根據注釋假定最后一行位於B方法的某處,則self
指向B的某個實例super
也指向B的同一實例。但是當您使用self
調用foo
,搜索foo
的實現始於類B。當您使用super
,對foo
的搜索始於B的超類A。
當您想保留繼承的行為,但要添加一些東西時, super
特別方便。 因此,我們可以讓B的foo
實現通過[super foo]
調用A的版本。 如果沒有super
,就無法調用繼承的方法,而從被覆蓋的方法中調用foo
將導致無限遞歸。
當您調用self
方法(或者用Objective-C術語向self
發送消息)時,運行時將在繼承層次結構中搜索該方法的實現,從self
開始,直至NSObject
。 因此,如果self
實現該方法,它將被執行。 如果沒有,將檢查super
類,依此類推。
發送消息到super
非常相似,除了運行時將開始在super
尋找實現並跳過self
。
有時候,在子類中,您可能會覆蓋父類中已經定義的函數。 通常,這在init函數中發生。 因此,如果您需要調用父類的init函數,則可以調用super。 如果您需要子類的功能,則可以調用self。 如果只有父對象聲明了該函數,則Self和super的行為相同。 但是,如果只有子類具有聲明,那么您將無法從super調用函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.