So there was this thread about using the Singleton pattern, and it went right quick into the usual whining about it being an anti-pattern and all, but there were a couple interesting links that turned up:
Singletons, AppDelegates and top-level Data is a good Cocoa-centric overview of the topic, and we direct your attention particularly to the SynthesizeSingleton.h header provided, which macroizes all the support you’d need if you wanted to use a singleton with conventional allocation semantics. Which strikes us as unlikely, but hey.
The interesting part though is the allocation question. The above-linked file relies on the @synchronized directive in allocation, which we think is a little unwieldy, as well as being Objective-C 2.0 dependent. So how to ensure thread safety then? Interesting discussions here, and here, and here, and here; that OSAtomicCompareAndSwapPtrBarrier idea strikes us as particularly nifty.
But here’s our idiom for setting up singletons; just do it at static initialization time, like this for initializing application settings:
static PMPESettings* _sSharedSettings = [PMPESettings sharedSettings];@implementation PMPESettings
+ (void)initialize{NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];[[self sharedSettings] load];[pool release];}
+ (PMPESettings *)sharedSettings{if (!_sSharedSettings)_sSharedSettings = [[self alloc] init];return _sSharedSettings;}
- (void)load{... if there aren't any saved settings, fill in defaults...}
@end
So long as we’re not doing ridiculous things at static initialization time — and oh boy, have we got some stories we could tell you about things we had to port that were completely dependent on Visual Studio’s link order! — but just sorting things into usable states, like above where -load creates default application preference values when none exist, this seems to me to be a perfectly reasonable way to leverage compiler and Objective-C semantics to sidestep synchronization worries completely. What do you all think?
h/t: iPhoneSDK!
UPDATES:
And if you want to read lots of advice on singleton implementation…
Ship-It Saturday: PRHEmptySingleton repository
Objective-C Singleton Class Template
Everyone has a singleton, and this is mine
Require OS 4? Hey, guaranteed alloc safety: Singletons: You’re doing them wrong
This looks like pretty much the final, universally compatible, word on the subject: Objective-C Singleton
MAY