[oc] instancetype vs id for Objective-C 【转】

原贴地址:http://blog.csdn.net/lyy_whg/article/details/12846055html

http://www.iwangke.me/2013/01/06/instancetype-vs-id-for-objective-c/ios

 

新的LLVM编译器为咱们带来了ARC, Object Literal and Scripting, Auto Synthesis等特性,同时也引入了instancetype关键字。instancetype用来表示Related Result Types(相关返回类型),那么它与id有什么不一样呢?objective-c

根据Cocoa的命名惯例,init, alloc这类的方法,若是以id做为返回类型,会返回类自己的类型。app

1
2
3
@interface Person
- (id)initWithName:(NSString *)name;
+ (id)personWithName:(NSString *)name;

但类方法的返回类型,LLVM(或者说Clang)却没法判断,咱们来看一段代码:post

1
2
3
// You may get two warnings if you're using MRC rather than ARC
[[[NSArray alloc] init] mediaPlaybackAllowsAirPlay]; // ❗ "No visible @interface for `NSArray` declares the selector `mediaPlaybackAllowsAirPlay`"
[[NSArray array] mediaPlaybackAllowsAirPlay]; // It's OK. But You'll get a runtime error instead of a compile time one

[NSArray array]除非显式转换为(NSArray *),不然编译器不会有错误提示。若是使用instancetype就不会有这样的问题:spa

1
2
3
@interface Person
- (instancetype)initWithName:(NSString *)name;
+ (instancetype)personWithName:(NSString *)name;

简单来讲,instancetype关键字,保证了编译器可以正确推断方法返回值的类型。这种技术基本从iOS 5的UINavigationController里就开始应用了。.net

Clang的文档里提到instancetype is a contextual keyword that is only permitted in the result type of an Objective-C method. 也就是说,instancetype只能做为返回值,不能像id那样做为参数。code

最后留个问题:Objective-C 3.0的时候,会不会出现泛型呢?htm

Reference:blog

相关文章
相关标签/搜索