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

后端 未结 9 956
爱一瞬间的悲伤
爱一瞬间的悲伤 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条回答
  •  旧时难觅i
    2020-12-09 18:55

    I had a similar problem, I had multiple targets that needed to have a slightly different singleton implementations: each target would include the base class + a specific subclass. This was achieved by writing the base class like so:

    + (SingletonBaseClass*) sharedInstance {
        static SingletonBaseClass * sharedInstance = nil;
        if (!sharedInstance) {
            sharedInstance = [[[self class] alloc] init];
            [sharedInstance customInit];
        }
        return sharedInstance;
    }
    

    The key difference is [self class] instead of the actual class name. That way when the we call: [SingletonSubclass sharedInstance] the correct object is instantiated.

    Please note that this is a specific case, in the general case I agree with previous answers.

提交回复
热议问题