Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does [NSDate date] return id?

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?

like image 732
user4234 Avatar asked Jan 03 '13 09:01

user4234


1 Answers

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.

like image 72
Gabriele Petronella Avatar answered Oct 31 '22 11:10

Gabriele Petronella