·您现在的位置: 云翼网络 >> 文章中心 >> 网站建设 >> app软件开发 >> IOS开发 >> instancetypevsidforObjective-C

instancetypevsidforObjective-C

作者:佚名      IOS开发编辑:admin      更新时间:2022-07-23

instancetype: 使用 instancetype 编译器和IDE 会做类型检查,而id不会做完整的类型检查。
A method with a related result type can be declared by using the type instancetype as its result type. instancetype is a contextual keyWord that is only permitted in the result type of an Objective-C method, e.g.
上面的话的意思:instancetype 是一个关键字,它只能用来定义OC方法的返回值类型。
id
A pointer to an instance of a class.
从上面的定义,就可以看出他们二者之间的区别。
      1. Explicit. Your code is doing what it says, rather than something else.
      2. Pattern. You're building good habits for times it does matter, which do exist.
      3. Consistency. You've established some consistency to your code, which makes it more readable

1. 显式的使用
  -(id)initWithBar:(NSInteger)bar;
  -(instancetype)initWithBar:(NSInteger)bar;
   在使用设计的构造方法时,编译器会自动将id翻译成instancetpye. 从技术本质上将,二者在这个时候是没有区别的。
   但是作为一个技术人员,应该用那个一个你懂得。
 
2. 模式  
+(id)fooWithBar:(NSInteger)bar;+(instancetype)fooWithBar:(NSInteger)bar;在使用便捷构造方法时,他们时不同的。在这里使用instancetype是有类型检查的。而id是没有类型检查的。
3. 一致性
If you use id for init, you end up with code like this:
- (id)initWithBar:(NSInteger)bar;
+ (instancetype)fooWithBar:(NSInteger)bar;
But if you use instancetype, you get this:
- (instancetype)initWithBar:(NSInteger)bar;
+ (instancetype)fooWithBar:(NSInteger)bar;
这样写虽然从本质上,看没有什么区别,当时代码的阅读可阅读性能够提高,并且便于理解。
http://blog.csdn.net/yangzychina/article/details/8818941
http://www.iwangke.me/2013/01/06/instancetype-vs-id-for-objective-c/
http://stackoverflow.com/questions/8972221/would-it-be-beneficial-to-begin-using-instancetype-instead-of-id