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:

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…

Objective-C Singleton Class Template

Everyone has a singleton, and this is mine

How I do my singletons

Require OS 4? Hey, guaranteed alloc safety: Singletons: You’re doing them wrong

Alex | May 7, 2009

Leave a Reply