instancetype vs class name for singleton?

后端 未结 2 1504
醉梦人生
醉梦人生 2021-02-19 07:36

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 alwa

2条回答
  •  有刺的猬
    2021-02-19 08:22

    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.

提交回复
热议问题