After reading the answers to the question about singles in Objective-C, it seems that every decision makes some trade-offs regarding streaming in an instance accessory. i.e.
@synchronized(self) { if (sharedInstance == nil) sharedInstance = [[MySingleton alloc] init]; } return sharedInstance;
This is essentially single-threaded access to singleton, and if it is something that is often used in the operation, it seems something that can cause unnecessary conflicts.
What is the disadvantage of simply using a class object as a singleton instance and exposing functionality using class methods, i.e.
@interface MySingleton : NSObject { } + (void)doSomething; @end @implementation MySingleton + (void)initialize { //do some setup if necessary } + (void)doSomething { //do something } @end
Thus, we avoid locking check + every time we want to refer to a singleton object, and we can also eliminate the need to store it in a local or ivar method.
This approach also allows the runtime to ensure that at any given time in the system there is only one instance (class object).
EDIT
Here is more than just streams, with a traditional singlet, you usually write this code:
MySingleton *instance = [MySingleton getSharedInstance]; NSObject *someResult = [instance getResult]; //or if (instance.someProperty) { //do something }
However, if your singleton is an instance of the class, you essentially eliminate the need to call getSharedInstance all the time. Consider this code:
NSObject *someResult = [MySingleton getResult]; //or if ([MySingleton someProperty]) { //do something }
I heard that you need to store your data in local static variables of the file or in global variables (yuck). But that's really not all that differs from the traditional singleton, except that you lose the properties of Objective-C 2.0 (you should use traditional access methods instead).
Here is one key compromise for me that seems like a victory. In a traditional singlet, you end up redefining -copyWithZone, + allocWithZone, -retain, -retainCount, -release and -autorelease if you really want to fix it.
This seems like a terrible job to do every time you want to write a simple Singleton object (they prove to be very useful). So why not just replace it with this:
@implementation MySingleton + (void)initialize {
This is much easier in terms of code, and if your consumers are really not vile, they will never create two instances.
Bring to the end My question is really this:
Is there a drawback to using the Class object as an instance of your singlet?
It seems that you can follow the same steps in terms of thread safety, memory efficiency, etc., without forgetting to redefine so many methods and accessories or substitute your code with instance checks.