instancetype 与 id for Objective-C

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;

但类方法的返回类型,LLVM(或者说Clang)却无法判断,我们来看一段代码:

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;

简单来说,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那样作为参数。


  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值