Nice Singleton in Obj-C

xcode.jpg

As part of this project I'm working on with a friend, I ran into the fact that in iOS development, Apple really doesn't allow the same level of control with custom objects that you can have with OS X development. For instance, it's very common in OS X development to have a controller class written in code and then instantiated in the xib, and wired up. It saves a lot of needless code of wiring up things, that's brittle and not really pushing the value of the app. My friends and I always called this Nib-ware, after the original NeXTSTEP Interface Builder files.

But what seems to be far more common in iOS is the idea of singletons. The key to making a good singleton is, of course, making sure that if you want only one, you get only one. And that usually means locking, or Compare and Swap - which is illegal with Automatic Reference Counting (ARC) code as it can't know if you got the swap or not. So when I found a simple way to make a singleton in Obj-C, I loved it's simplicity and beauty.

The header is simple enough:

  /*!
   This class method is the singleton of the PKBClient for the entire app.
   The first call to this method will create the singleton and initialize
   it for all uses. All state for the connection to the back-end will be
   stored in this one instance.
   */
  + (id) sharedClient;

and the implementation is just lovely:

  + (id) sharedClient {
      static PKBClient*	shared = nil;
      static dispatch_once_t onceToken;
      dispatch_once(&onceToken, ^{
          shared = [[self alloc] init];
      });
      return shared;
  }

So simple... a static value and then a simple block to initialize it, but the magic is in the dispatch_once - that's really exceptional. Sure, clojure has this, and a lot of other languages do, but this is the first time I've seen it in a C/C++/Obj-C language, and it makes so many things so much easier.

It's nice to work with good tools.