instancetype
关键字,它可以表示一个方法的相关返回类型。
例如:
@interface Person
+ (instancetype)personWithName:(NSString *)name;
@end
instancetype
与id
不一样,instancetype
只能在方法声明中作为返回类型使用。
使用 instancetype
,编译器将正确的推断出 +personWithName:
是 Person
的一个实例。
用instancetype代替id作为返回值的确没有技术上的好处。但这是因为编译器自动将id转化成了instancetype。你以为init返回的值类型是id,其实编译器返回了instancetype。