instancetype vs class name for singleton?
Asked Answered
T

2

14

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?

Threecolor answered 24/5, 2013 at 20:51 Comment(0)
V
18

instancetype is useful for situations involving inheritance. Consider you have class A which inherits from class B. A method in B which returns an instance of B may be declared previously as id, its override in A may return an instance of A - which is all good but the compiler has no clue. However by using instance type the compiler is informed that when called on an A instance that the method returns an A instance, and so can give better diagnostics, code completion, etc.

Now in your example you've used MyClass * rather than id, 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 of MyClass), are you likely to define another class which inherits from MyClass and overrides the sharedInstance method? Probably not, but if you do instancetype may be of use, otherwise it gains nothing.

Vermouth answered 24/5, 2013 at 21:24 Comment(2)
I would argue that allowing for the flexibility to subclass inherently gains "something" and is a best practice, regardless of the likelihood of subclassing in the immediate future. Unlike the use of id, with instancetype, we ensure that the compiler is checking type so we gain flexibility without being ambiguous.Vitalism
This answer has a note about how subclassing singletons can cause problems. https://mcmap.net/q/829526/-definite-class-name-in-a-singleton-methodShuster
L
4

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.

Literalminded answered 24/5, 2013 at 21:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.