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 作为返回值。