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

后端 未结 9 953
爱一瞬间的悲伤
爱一瞬间的悲伤 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:45

    I had a similar problem and the way I solved it is to create a singleton wrapper class which has all the extra functionality. This singleton class contains the original singleton (has the singleton instance as a member variable). This way you can avoid dirty tricks.

    0 讨论(0)
  • 2020-12-09 18:52

    Jon Skeet makes a good point about whether you’d really have a singleton if you’re allowed to instantiate both the class and its subclass. Putting that aside, here’s a pattern you can use so that so you only have to define the shared-instance getter once, in the parent class:

    // this code goes in the implementation of the superclass
    
    static Sprocket *defaultSprocket;
    
    + (instancetype) defaultSprocket
    {
        if (defaultSprocket == nil)
            defaultSprocket = [[[self class] alloc] init];
        return defaultSprocket;
    }
    

    This approach has the following advantages:

    • Using [self class] allows e.g. [SprocketSubclass defaultSprocket] to return an instance of SprocketSubclass instead of Sprocket
    • Using instancetype allows the compiler to type-check the result of this method: it’ll be Sprocket when you invoke it as +[Sprocket defaultSprocket] but SprocketSubclass when you invoke it as +[SprocketSubclass defaultSprocket].

    Notably, you can define this accessor method in the base class and then you don’t have to do anything in the subclasses!

    (Hat tips to NSHipster for explaining why instancetype is so cool and bbum for reminding me of it recently.)

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题