instancetype 与id

 1 .依照cocoa的命名规则,allocinit这类方法,如果以id为返回类型,会返回类本身的类型,但类方法的返回类型,LLVMclang)编译器无法判断,也就是说如果       用id作为返回类型,有可能会将一个编译时错误变为一个运行时错误,instancetype则能够保证编译器正确判断返回的类型。

2.  instancetype只能作为返回值,不能像id那样作为参数。

3 .+ (id)fooWithBar:(NSInteger)bar;  编译器不会自动将id 转换成 instancetype 

   对于 init,他变得更加的复杂。比如当你写成如下格式

    - (id)initWithBar:(NSInteger)bar

    - (id)initWithBar:(NSInteger)bar

   编译器会用如下形式保护起来: 

- (instancetype)initWithBar:(NSInteger)bar

当你自定义初始化方法后 如果放回的是 id  然后调用其它类的方法时 编译时是不会报错 只有在运行时会报错 

所以在你自定义初始化方法时 让放回值为 instancetype 

  

原文地址:https://www.cnblogs.com/studyios/p/3698467.html