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
新聞熱點
疑難解答