< Back

# instancetype vs. id

Bringing it to the point, using

- (instancetype)initWithFoo:(BOOL)bar

has no technical advantage over

- (id)initWithFoo:(BOOL)bar

except for code consistency. As the compiler automatically translates id to instancetype. It’s different with convenience constructor methods as an id won’t get translated to instancetype there:

+ (id)initWithFoo:(BOOL)bar

will return a generic object as where

+ (instancetype)initWithFoo:(BOOL)bar

will return an object of class “instancetype”.

Thus, you got to take special care when instantiating singletons as it may easily conflict with the singleton pattern.

Say you’ve got a class called MySingleton and you’d like to subclass this class and instantiate it using

- (instancetype)sharedInstance

what happens is that if the sharedInstance method is called on the subclass, it will either return the object created by the base class, which will be of the wrong type else it will create another instance and violate the singleton pattern.

This can easily be solved by providing the singleton constructor with an explicit type.

Whenever writing a method returning id ask your self, wouldn’t my method return and instance of it’s class? Then use instancetype.

Cheers!

Impressum • Mastodon