Objective-C Singletons

Template for a singleton

2019

While singletons are often overused that doesn’t mean there isn’t a place for them. It also doesn’t mean there isn’t a way to implement them that addresses some of the concerns of critics.

Shared Instance

Rather then looking at singletons as the sole instance of a class I prefer the shared instance perspective. That being there exists a shared global instance that does not negate the possibility of other instances.

The current recommended approach to implementation is to lazily create the shared instance with a method structurally similar to +initialize. Inside the method would be a static variable to hold the instance as well as a dispatch_once() in which the instance is initialized. That being said in order to provide other instances any initialization work should be done in the instance initializer which should be publicly accessable.

SomeSharedClass.h
@interface SomeSharedClass : NSObject

+ (instancetype)sharedInstance;

- (instancetype)init NS_DESIGNATED_INITIALIZER;

@end
SomeSharedClass.m
+ (instancetype)sharedInstance
{
	static SomeSharedClass *sharedInstance = nil;
	static dispatch_once_t onceToken;
	dispatch_once(&onceToken, ^{
		sharedInstance = [[self alloc] init];
	});

	return sharedInstance;
}

- (instancetype)init
{
	if ( (self = [super init]) )
	{
		// Do the actual initialization work.
	}
	return self;
}

This approach has the benefits of only producing a single shared instance, that is created lazily, and may be used outside the singleton pattern.

	SomeSharedClass *singleton = [SomeSharedClass sharedInstance];
	SomeSharedClass *anotherInstance = [[SomeSharedClass alloc] init];

Licence

Any source in this article is released under the ISC License.