From what I understand, instancetype declares to the compiler that the return type of the method is the same as the class receiving the message.
Traditionally I've always declared my singleton initializers with the class name explicitly set as the return type:
@interface MyClass : NSObject
+ (MyClass *)sharedInstance;
@end
Now I'm wondering if I should use instancetype instead, like so:
@interface MyClass : NSObject
+ (instancetype)sharedInstance;
@end
In the end the result is the same, I'm just wondering if there's a reason to use one or the other here?
instancetype
is useful for situations involving inheritance. Consider you have classA
which inherits from classB
. A method inB
which returns an instance ofB
may be declared previously asid
, its override inA
may return an instance ofA
- which is all good but the compiler has no clue. However by using instance type the compiler is informed that when called on anA
instance that the method returns anA
instance, and so can give better diagnostics, code completion, etc.Now in your example you've used
MyClass *
rather thanid
, so you've already told the compiler the type. You also have a shared instance model (not a singleton model as you can other instances ofMyClass
), are you likely to define another class which inherits fromMyClass
and overrides thesharedInstance
method? Probably not, but if you doinstancetype
may be of use, otherwise it gains nothing.Constructor methods traditionally have returned
id
, allowing subclasses to use them too.id
, of course, means "any object at all".instancetype
was introduced to give a little more type strictness when assigning the result of a constructor method.It's only useful in case of subclassing. If that method will never be overridden, it's better to be as explicit as possible and use the actual class name.