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

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

    I had the same problem. This is how to solve: You need to use a static dictionary to subclass a singleton. For exemple:

    Class A : NSObject -> Singleton

    Class B : A

    Class C : A

    @implementation A
    
    // Dictionary that holds all instances of API subclasses
    static NSMutableDictionary *_sharedInstances = nil;
    
    + (instancetype)sharedInstance
    {
        id sharedInstance = nil;
        @synchronized(self)
        {
           NSString *instanceClass = NSStringFromClass(self);
    
           if (_sharedInstances == nil)
               _sharedInstances = [NSMutableDictionary dictionary];
    
           // Looking for existing instance
           sharedInstance = [_sharedInstances objectForKey:instanceClass];
    
           // If there's no instance – create one and add it to the dictionary
           if (sharedInstance == nil) 
           {
              sharedInstance = [[super allocWithZone:nil] init];
              [_sharedInstances setObject:sharedInstance forKey:instanceClass];
           }
       }
       return sharedInstance;
    

    }

    Now you can use [B sharedInstance] and [C sharedInstance] without problems!

提交回复
热议问题