[oc] instancetype vs id for Objective-C 【转】
来源:互联网 发布:淘宝的极速退款是什么 编辑:程序博客网 时间:2024/06/08 04:19
原贴地址: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作为返回类型,会返回类本身的类型。
123
@interface Person- (id)initWithName:(NSString *)name;+ (id)personWithName:(NSString *)name;
但类方法的返回类型,LLVM(或者说Clang)却无法判断,我们来看一段代码:
123
// 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就不会有这样的问题:
123
@interface Person- (instancetype)initWithName:(NSString *)name;+ (instancetype)personWithName:(NSString *)name;
简单来说,instancetype关键字,保证了编译器能够正确推断方法返回值的类型。这种技术基本从iOS 5的UINavigationController里就开始应用了。
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
- [oc] instancetype vs id for Objective-C 【转】
- instancetype vs id for Objective-C
- instancetype vs id for Objective-C
- instancetype vs id for Objective-C
- instancetype vs id for Objective-C
- instancetype vs id for Objective-C
- instancetype 与 id for Objective-C
- instancetype 与 id for Objective-C
- Objective-C id和instancetype
- Objective-C:instancetype与id
- Objective-C中的instancetype和id关键字
- Objective-C中的instancetype和id区别
- Objective-C中的instancetype和id关键字
- Objective-C中的instancetype和id关键字
- Objective-C中的instancetype和id关键字
- Objective-C中的instancetype和id关键字
- Objective-C中的instancetype和id区别
- Objective-C中的instancetype和id关键字
- [JAVA] 学java必看书籍
- [ios2]Emoji表情符号兼容方案 【转】
- [ios2]BaaS服务收藏 【转】
- [ios2] iOS 7新功能的代码例子 【转】
- [ios3-地图] 如何在iOS地图上高效的显示大量数据 [转]
- [oc] instancetype vs id for Objective-C 【转】
- [ios-必看] WWDC 2013 Session笔记 - iOS7中的多任务【转】
- [ios-必看] 国人当自强:两岸三地在线编程学习网站大搜罗 [转]
- [ios-必看] IOS调试技巧:当程序崩溃的时候怎么办 iphone IOS
- [ios-必看] iOS 下实现解压缩
- [.net] c# webservice
- [ios] CGRect
- [ios] NSURL
- [ios] coreText