Static Class vs Singleton
cocoa, ios, macos, objective-c
Solution
You're pissing off no Objective-C gods with a class like that. Actually, Apple recommends to use that pattern in some cases (I think they mentioned this in one of the ARC session videos, where they discussed common design patterns and how to implement them using ARC).
In other cases, where you can have multiple instances of a class, but want a default one, you'll of course have to use the shared instance approach.
Problem
So, pretty simple question. Ignoring the implications of over-use of the singleton pattern. I'm trying to find a reliable singleton patter in Objective-C. I have come across this: ``` @implementation SomeSingleTonClass static SomeSingleTonClass* singleInstance; + (SomeSingleTonClass*)getInstance { static dispatch_once_t dispatchOnceToken; dispatch_once(&dispatchOnceToken, ^{ singleInstance = [[SomeSingleTonClass alloc] init]; }); return singleInstance; } - (void)someMethodOnTheInstance { NSLog(@"DO SOMET WORK") } @end ``` This I am fairly happy with but it leads to a lot of this: ``` [[SomeSingleTonClass getInstance] someMethodOnTheInstance]; ``` My question is, why is this better than a purely static class. ``` @implementation SomeStaticClass static NSString* someStaticStateVariable; - (id)init { //Don't allow init to initialize any memory state //Perhaps throw an exception to let some other programmer know //not to do this return nil; } + (void)someStaticMethod { NSLog(@"Do Some Work"); } ``` All you really gain, is mildly cleaner looking method calls. Basically you swap out this: ``` [[SomeSingleTonClass getInstance] someMethodOnTheInstance]; ``` For this ``` [SomeStaticClass someStaticMethod]; ``` This is a minor simplification for sure, and you can always store the instance within your class. This is more intellectual curiosity, what Objective-C god am I pissing off by using static classes instead of singletons? I'm sure I can't be the first person to think this, but I promise, I did a duplicate search first. The few answers I found, I felt like were based on older versions of cocoa, because even the discussed singleton patterns seemed to suffer from threading issues.