Managing Multiple Singleton Classes in Objective-C

There are already numerous articles describing different approaches to using singletons in Objective-C. All aproaches have their upsides and downsides, and I won’t get into that discussion here. Here’s what I wanted from my singleton implementation:

  1. It has to be in one class, which every class wanting to be a singleton must subclass, and by doing so it would get all the singleton functionality “for free”.
  2. It needs to provide a mechanism to kill all instantiated singletons on demand, with one static function call.

Point number 2 is important in a situation where (for example) you have a certain subsystem in your application that is needed only from time to time. Once you’re done with using the subsystem, you don’t want a bunch of its singletons lying around and taking up memory.

A typical singleton approach in Objective-C is to have a single static variable defined in your implementation file that acts as the actual singleton. This is all fine and dandy if you’re amused with rewriting your singleton code in every class that needs to act as a singleton. Personally, if I see the same piece of code scattered around the project, I get pretty pissed off. (See the subtitle of this blog?) Sure, you could just define all the singleton code as a preprocessor macro, and then use that macro in every class declaration, but in my opinion preprocessor macros are bad, bad practice.

So, you can’t use this approach here, because we want to be able to subclass this Singleton class. When you create an instance of the SingletonA class, the static variable inside the Singleton class points to an instance of SingletonA. If you would then request an instance of the SingletonB class in your code, you would get the reference to SingletonA‘s instance variable, since there’s only one variable holding the instance reference, and it’s defined in the base Singleton class. You can work around this problem by introducing additional subclass code, but remember that this is exactly what we want to avoid.

Here’s what I came up with:


Since we need to keep track of multiple subclass instances, we need to have some kind of a collection that remembers each class’ instance. I’m using an NSDictionary, with Class objects as keys, and actual singleton instances as values. (Remember, self refers to the Class value inside class methods.) You can use [SingletonA destroyInstance] to destroy an instance of SingletonA, because instances are mapped by Class values. You can destroy all instances ever created by simply calling [Singleton destroyAllSingletons].

The upside of this approach is that all you have to do to turn your class into a singleton is to subclass the Singleton class. That’s it.

The downside (obviously) is that you’re spending time on dictionary lookup every time you need to fetch a particular instance. I found this to be a practically non-existent issue if you’re using singletons outside of any heavy loops. For example, you should do:

SingletonA singleton = [SingletonA instance];
for (...) {
    [singleton doSomething];
}

instead of:

for (...) {
    [[SingletonA instance] doSomething];
}

That way you’re only fetching from the dictionary once.

2 responses to “Managing Multiple Singleton Classes in Objective-C”

  1. Francisco Valbuena

    Nice article, I have been asking my self the best way to do what you did.

    Thanks.

  2. Srini

    Great article, I modified it a little bit to make it thread safe.

    static NSMutableDictionary *_sharedInstances;
    static dispatch_once_t token;

    + (id)sharedInstance {
    dispatch_once(&token, ^{
    _sharedInstances = [[NSMutableDictionary alloc] init];
    });
    NSString *key = NSStringFromClass([self class]);
    id instance = [_sharedInstances objectForKey:key];
    if (!instance) {
    @synchronized(self) {
    id instance = [[self alloc] init];
    [_sharedInstances setObject:instance forKey:key];
    }
    }
    return instance;
    }

Leave a Reply