Archive for May 7th, 2009

07
May

Snippet: Singletons

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!