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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With