instancetype 与 id for Objective-C
来源:互联网 发布:plc编程难吗 编辑:程序博客网 时间:2024/05/20 10:54
本文转载于:http://blog.csdn.net/cancer1617/article/details/21372353
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那样作为参数。
0 0
- instancetype 与 id for Objective-C
- instancetype 与 id for Objective-C
- Objective-C:instancetype与id
- 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
- [oc] instancetype vs 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关键字
- 黑马程序员-----C语言学习之通讯录应用的代码实现
- ny1055
- 存储过程操作
- 暑假集训第三周 STL R - What Are You Talking About
- Python 之 h5py 读取 matlab 中 .mat 文件 cell 方法浅析
- instancetype 与 id for Objective-C
- 全局变量,static ,extern(cp:http://blog.csdn.net/it_youhun/article/details/8526147)
- 黑马程序员------OC 面向对象和面向过程思想(基础)
- Pinyin4j的基本用法
- 一些前端的心得体会,笔记
- Spring的Bean的生命周期
- C++中指针和引用的区别与联系
- hdu-1509 Windows Message Queue(优先队列)
- Text Justification