- instancetype is a contextual keyword that can be used as a result type to signal that a method returns a related result type.
@interface Person
+ (instancetype)personWithName:(NSString *)name;
@end
使用id类型,当指针类型不匹配时,编译器不报错:
@interface Foo : NSObject
+ (id)aConvenienceInit;
@end
/// 编译器不报错
NSArray* subviews = [Foo aConvenienceInit].subviews;
使用instance类型,当指针类型不匹配时,编译器报错:
@interface Foo : NSObject
+ (instancetype)aConvenienceInit;
@end
/// 编译器报错
NSArray* subviews = [Foo aConvenienceInit].subviews;
- instancetype, unlike id, can only be used as the result type in a method declaration. instancetype只能用于方法声明时的返回值,id的用法更广泛。
参考资料:
https://stackoverflow.com/questions/36020540/why-is-instancetype-used
https://nshipster.com/instancetype/









网友评论