Luda
Luda

Reputation: 7068

Can Singleton Inheritance be achieved in iOS

I have couple of classes that should be inherited from some A class.

Each of them should be a Singleton.

Can this be achieved?

Upvotes: 1

Views: 1328

Answers (3)

gnasher729
gnasher729

Reputation: 52538

You never, ever inherit from a Singleton class. That completely breaks the concept of a Singleton in a bad way.

Having multiple singleton classes inheriting from the same base class: No problem whatsoever. In fact, most singletons have the common superclass NSObject, but you can use any other superclass.

Upvotes: 2

Mikhail
Mikhail

Reputation: 1071

This realization of Singleton-pattern allows the inheritance:

+ (instancetype)sharedInstance {

    static dispatch_once_t once;
    static NSMutableDictionary *sharedInstances;

    dispatch_once(&once, ^{ /* This code fires only once */

        // Creating of the container for shared instances for different classes
        sharedInstances = [NSMutableDictionary new];
    });

    id sharedInstance;

    @synchronized(self) { /* Critical section for Singleton-behavior */

        // Getting of the shared instance for exact class
        sharedInstance = sharedInstances[NSStringFromClass(self)];

        if (!sharedInstance) {
            // Creating of the shared instance if it's not created yet
            sharedInstance = [self new];
            sharedInstances[NSStringFromClass(self)] = sharedInstance;
        }
    }

    return sharedInstance;
}

Upvotes: 10

Colin Cornaby
Colin Cornaby

Reputation: 746

Yes. I'm not sure if you're familiar with Obj-C singleton patterns, but here is a guide: http://www.galloway.me.uk/tutorials/singleton-classes/

There shouldn't be any more complications in subclassing. Just create a subclass of the singleton, and it will inherit it's singleton abilities as well. I think each subclass will create it's own unique singleton, but if not, override the singleton generator so it's unique for that subclass.

Keep in mind, singletons are falling out of favor on iOS, so they should be used sparingly. I try to only use them when attempting to create multiple instances is simply not possible (i.e. a class for accessing a hardware resource that must be reserved exclusively by a class.)

Upvotes: 0

Related Questions