User Tools

Site Tools



A design pattern for dealing with the issue of exposing a common interface to many objects without passing a reference to that object around. (if interested, read up on design patterns. Delegation is also a design pattern)

The defining characteristic of a singleton is there can only be one. Repeated calls to the accessor method of a singleton always return a reference to the original object. This allows objects to “instantiate” the singleton many times, but retrieve the same object.

WARNING: Singletons are dangerous. Their convenience and usefulness allows developers to abuse them easily for the exact same reason global variables are dangerous. They can potentially massively increase inter-project dependencies, can be difficult to test, and are easily broken by inconsistent application of usage. Do not use a singleton unless you've clearly identified a situation in which to use it.

To create a singleton:

  1. create a class method that returns type id
  2. create dispatch_once method in that method implementation

Example from DriveSense project for singleton named TripRecorder with accessor method recorder: Class method in header file (this is the method called that will return the singleton)

+ (id)recorder;

Method implementation in .m file:

+ (id)recorder {
    static TripRecorder *recorder = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        recorder = [[self alloc] init];
    return recorder;

dispatch_once is a C method part of GCD (Grand Central Dispatch), a method of coordinating and synchronizing threads. The contents of the block will only be called once. The instance is stored in the static variable recorder and is returned at the end of every accessor call.

Example invocation of singleton accessor, returning singleton:

[TripRecorder recorder]

Note that the init method of the singleton is still called when the singleton is created, you should put initialization code here.

ios-labs-s14/advanced-singleton.txt · Last modified: 2014/02/24 13:10 by mbarboi