Fundamental iOS design patterns: SharedInstance (Singleton in Objective C)

Brief introduction

Singleton is one of the (if not THE) most commonly used/abused design pattern adopted in software development.
Basically it’s used to restrict the instantiation of a class to one object only that can be used safely across application architecture. Its implementation is pretty simple compared to other patterns and it’s very similar for the most of programming languages, but in Objective C it has a slightly different approach due to the lack of “normal constructor” that are instead replaced by alloc/init paradigm.

How it works in Objective C

In Objective C, we can speak more appropriately about the SharedInstance pattern rather than traditional Singleton.
This one is often used in Apple frameworks and differently from its twin brother, it does not explicitly forbid the instantiation of multiple class instances, but it simply provide a class method that will return a shared instance. During the first call to that method the instance will be allocated and the next calls will return the previously object created. So this is a sort of hybrid approach.
A common class that use this pattern is UIApplication which implements a sharedApplication method (which returns the current running application). Differently from Singleton which use getInstance(), in Objective C the corresponding method has not a fixed name but it should start with “shared” followed by the “type” of class (so for UIApplication is “sharedApplication” for MYAmazingManager will be “sharedManager“). Anyway there are several exceptions, for example NSFileManager has a “defaultManager” acting as a sharedInstance accessor that could be renamed “sharedManager“.

Pattern implementation

In my singleton implementations I simply call the accessor “sharedInstance“, in this way I can use a simple pre-compiler macro that automatically synthesize this methods for me.
Even implementation of this pattern may vary and personally I adopted one which is thread-safe and rely on CGD (Grand Central Dispatch), which is an affective C level API provided by Apple in order to handle concurrency.

The implementation of my sharedInstance method is the following (comments explain how it works):

+ (id)sharedInstance 
{
	// structure used to test whether the block has completed or not
	static dispatch_once_t p = 0;
	
	// initialize sharedObject as nil (first call only)
	__strong static id _sharedObject = nil;
	
	// executes a block object once and only once for the lifetime of an application
	dispatch_once(&p, ^{
		_sharedObject = [[self alloc] init];
	});
	
	// returns the same object each time
	return _sharedObject;
}

Pattern in action!

SharedInstance pattern is IMO the best way to share data across multiple viewControllers in iOS applications.
One practical example is a data manager to share Core Data stuff such managed object context. I realized my own manager so that I can access this objects anywhere with ease like:

[[MYDataManager sharedInstance] managedObjectContext];

8 thoughts on “Fundamental iOS design patterns: SharedInstance (Singleton in Objective C)

  1. Nicolas Miari

    I usually have the ‘sharedInstance’ variable as file-static (outside if the method); a remnant from the old days of bloated singletons that override retain, release, copyWithZone, etc…

    Perhaps moving it back in (method-static) would be more compact/elegant.

  2. Dinesh

    Hi , I am trying to understand singleton,correct me if i am wrong here:

    When i call sharedInstance many times, the local variables sets the value again to
    static dispatch_once_t p = 0;
    __strong static id _sharedObject = nil;

    Then again new object will be creating .Then how come this implement singleton.

  3. Dinesh

    Hi, You accepted my comment . But not sure why there is no answer for my question…please help to understand this concept…

Leave a Reply