[oc] instancetype vs id for Objective-C 【转】
2013-12-17 09:43
204 查看
原贴地址:http://blog.csdn.net/lyy_whg/article/details/12846055
http://www.iwangke.me/2013/01/06/instancetype-vs-id-for-objective-c/
新的LLVM编译器为我们带来了ARC, Object Literal and Scripting, Auto Synthesis等特性,同时也引入了instancetype关键字。instancetype用来表示Related Result Types(相关返回类型),那么它与id有什么不同呢?
根据Cocoa的命名惯例,init, alloc这类的方法,如果以id作为返回类型,会返回类本身的类型。
但类方法的返回类型,LLVM(或者说Clang)却无法判断,我们来看一段代码:
简单来说,instancetype关键字,保证了编译器能够正确推断方法返回值的类型。这种技术基本从iOS 5的UINavigationController里就开始应用了。
Clang的文档里提到
最后留个问题:Objective-C 3.0的时候,会不会出现泛型呢?
Reference:
ClangClang Language Extensions
NSHipster
Typed Collections With Self Types in Objective-C
http://www.iwangke.me/2013/01/06/instancetype-vs-id-for-objective-c/
新的LLVM编译器为我们带来了ARC, Object Literal and Scripting, Auto Synthesis等特性,同时也引入了instancetype关键字。instancetype用来表示Related Result Types(相关返回类型),那么它与id有什么不同呢?
根据Cocoa的命名惯例,init, alloc这类的方法,如果以id作为返回类型,会返回类本身的类型。
1 2 3 | @interface Person - (id)initWithName:(NSString *)name; + (id)personWithName:(NSString *)name; |
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就不会有这样的问题:
1 2 3 | @interface Person - (instancetype)initWithName:(NSString *)name; + (instancetype)personWithName:(NSString *)name; |
Clang的文档里提到
instancetype is a contextual keyword that is only permitted in the result type of an Objective-C method.也就是说,instancetype只能作为返回值,不能像id那样作为参数。
最后留个问题:Objective-C 3.0的时候,会不会出现泛型呢?
Reference:
ClangClang Language Extensions
NSHipster
Typed Collections With Self Types in Objective-C
相关文章推荐
- 每日一Vim(18)Text-Object
- java.util.Hashtable.containsKey(Object key)方法实例
- iOS(iPhone,iPad))开发(Objective-C)开发库常用库索引
- 黑马程序员_温习 IO流四 (个人笔记)摘要(打印流PrintWriter(Stream)---序列流SwquenceInputStream----对象流ObjectInputStream(Outp
- java多线程同步块(synchronized(Object o){})的一个例程
- ios中json object转换成字符串
- Objective-C基本数据类型整理
- The type java.lang.Object cannot be resolved. It is indirectly referenced from required .class files
- 线程中CreateEvent和SetEvent及WaitForSingleObject的用法
- WaitForSingleObject 的用法
- object.getAttribute() setAttribute()
- 树形图dhtmlXTreeObject
- dhtmlXTreeObject 部分方法
- Objective-C关键知识点
- Objective-c中数字型字符串转换NSNumber的三种方法
- XI.spring的点点滴滴--IObjectFactoryPostProcessor(工厂后处理器)
- objective-c数组使用小结
- Objective-C的内省(Introspection)小结
- PHP-Open Flash Chart学习一(swfobject知识)
- nil、Nil、NULL、NSNull、[NSNull null] in Objective-C