What's the correct method to subclass a singleton class in Objective -C?

后端 未结 9 920
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-09 18:23

I have created a singleton class and I want to create a class which is subclass of this singleton class, what is the correct method to do it

9条回答
  •  伪装坚强ぢ
    2020-12-09 18:42

    The simplest way to achieve this is implement the standard singleton accessor in both the class and the subclass. This way each class behaves as a proper singleton, that is there is only ever one instance of both. If you attempt to reuse the accessor of the parent class in the subclass and then if you make use of both classes, you run the risk of the accessor returning the wrong instance because their behaviour would depend on the order of how they are accessed.

    You should not use instancetype for the singleton accessor to help prevent this mistake. You'll notice Apple don't use it for their singletons e.g. UIApplication and CKContainer.

    If you would like existing code that accesses the super-class's singleton method be given an instance of the subclass then likely you need to redesign, see MrJre's answer.

提交回复
热议问题