为什么 [NSDate date] 返回 id? [英] Why does [NSDate date] return id?
问题描述
为什么不返回NSDate*
?
应该是创建函数吧?所有创建函数都返回类型为创建它的类的类.
It's supposed to be a creation function right? All creation function return the class whose type is the class creating it.
现在,我不能做 NSDate.date.timeIntervalSince1970
:(
Now, I can't do NSDate.date.timeIntervalSince1970
:(
我认为编译器足够聪明,知道 NSDate.date 返回 NSDate,即使返回类型是 id?
I thought the compiler is smart enough to know that NSDate.date return NSDate even though the return type is id?
推荐答案
UPDATE
从 iOS 7 开始,Apple 使用 instancetype
作为大多数 Foundation 框架 API(以及其他框架)的返回类型,所以现在例如 +date
NSDate
的签名如下:
UPDATE
Starting from iOS 7, Apple is using instancetype
as return type for most of the Foundation framework APIs (and other frameworks too), so now for instance the +date
of NSDate
has the following signature:
+ (instancetype)date
我刚刚写了一篇短文 关于它.
I just wrote a short article about it.
构造函数和工厂方法返回 id
以允许子类使用它们而无需过度使用.
Constructors and factory methods return id
in order to allow subclasses to use them without ovverriding.
假设您有一个 NSDate
的子类,名为 NSMutableDate
.
Imagine you have a subclass of NSDate
called NSMutableDate
.
如果你打电话
[NSMutableDate date]
现在您希望返回一个 NSMutableDate *
对象,但是如果 date
正在返回 NSDate *
您将需要覆盖它改变返回类型的方法.
now you would expect to have a NSMutableDate *
object back, but if date
was returning NSDate *
you would have needed to override that method changing the return type.
使用 id
可以实现这种灵活性.
Using id
allows this kind of flexibility.
实际上,clang 编译器有 instancetype
关键字,在您定义自己的工厂方法时会派上用场.我最近谈到了这个具体问题 此处.
Actually the clang compiler has the instancetype
keyword that comes in handy in case you are defining your own factory methods.
I recently talked about this specific issue here.
这篇关于为什么 [NSDate date] 返回 id?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!