原貼地址: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