instancetype 返回型別
Objective-C 支援一種名為`instancetype 的特殊型別,它只能用作方法返回的型別。它計算接收物件的類。
考慮以下類層次結構:
@interface Foo : NSObject
- (instancetype)initWithString:(NSString *)string;
@end
@interface Bar : Foo
@end
呼叫 [[Foo alloc] initWithString:@"abc"]
時,編譯器可以推斷返回型別為 Foo *
。Bar
類派生自 Foo
,但沒有覆蓋初始化程式的宣告。然而,由於 instancetype
,編譯器可以推斷 [[Bar alloc] initWithString:@"xyz"]
返回 Bar *
型別的值。
考慮 -[Foo initWithString:]
的返回型別是 Foo *
:如果你要呼叫 [[Bar alloc] initWithString:]
,編譯器會推斷返回 Foo *
,而不是 Bar *
,這是開發人員的意圖。instancetype
解決了這個問題。
在引入 instancetype
之前,初始化器,靜態方法(如單例訪問器)和其他想要返回接收類例項的方法需要返回 id
。問題是 id
意味著 任何型別的物件 。因此,編譯器無法檢測到 NSString *wrong = [[Foo alloc] initWithString:@"abc"];
正在為具有不正確型別的變數分配。
由於這個問題,初始化者應該始終使用 instancetype
而不是 id
作為返回值。