Why does [NSDate date] return id?

折月煮酒 提交于 2019-12-10 12:49:47

问题


Why doesn't it return NSDate*?

It's supposed to be a creation function right? All creation function return the class whose type is the class creating it.

Now, I can't do NSDate.date.timeIntervalSince1970 :(

I thought the compiler is smart enough to know that NSDate.date return NSDate even though the return type is id?


回答1:


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.

Original answer

Constructors and factory methods return id in order to allow subclasses to use them without ovverriding.

Imagine you have a subclass of NSDate called NSMutableDate.

If you call

[NSMutableDate date]

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.

Using id allows this kind of flexibility.

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.




回答2:


The class factory methods (such as [NSMutableDate date], [NSMutableArray array], etc.) internally use alloc/init, and return whatever init returns.

init and its siblings (initWith...) always return an id, and by extension, so do the class factory methods.




回答3:


It's a factory method providing a convenient way of creating new auto-released objects.

See this Apple guide.



来源:https://stackoverflow.com/questions/14136271/why-does-nsdate-date-return-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!