Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 757
Ravindra Soni Avatar asked Aug 03 '10 06:08

Ravindra Soni


People also ask

What is the best way to subclass singleton?

I would argue the most common way to implement a singleton is to use an enum with one instance. That might be a "better" way but definitely not the most common way. In all the projects I have worked on, Singletons are implemented as I have shown above.

What is singleton class in Objective C?

What is a Singleton Class? A singleton class returns the same instance no matter how many times an application requests it. Unlike a regular class, A singleton object provides a global point of access to the resources of its class.

Can singleton class have subclass?

Yes. A singleton class has a private constructor which is not accessible to any other class inside the same package or outside. Hence it cannot be sub classed from any other class.

What is the Singleton pattern in object oriented programming when would you use it?

In software engineering, the singleton pattern is a software design pattern that restricts the instantiation of a class to one "single" instance. This is useful when exactly one object is needed to coordinate actions across the system.


2 Answers

I don't know about Objective-C in particular, but in general singleton classes should prevent subclassing. If you've got an instance of the base class and an instance of the subclass, then you've effectively got two objects you can regard as instances of the base "singleton" class, haven't you?

As soon as you've got two instances, it's not really a singleton any more... and that's leaving aside the possibilities that there are multiple subclasses, or that the subclass itself allows multiple instances to be created.

Of course you can change your base class so it just has a way of getting at a single "default" instance, but that's not quite the same as making it a singleton.

like image 57
Jon Skeet Avatar answered Sep 28 '22 10:09

Jon Skeet


If Jon didn't convinced you to not do it, you should do it this way:

In your superclass, init your singleton instance with [[[self class] alloc] init] so then you always get an instance of the class with which you are calling the sharedInstance method. And you don't have to overwrite the sharedInstance method in your subclass.

 [SuperClass sharedInstance] //-> instance of SuperClass
 [SubClass sharedInstance] //-> instance of Class
like image 20
V1ru8 Avatar answered Sep 28 '22 09:09

V1ru8