Singleton in Objective-C, One and Only One

Gunawan Lie
2 min readNov 1, 2020

Singleton is a design pattern that commonly used to design a class, such that only one instance of that class is expected to exist in the application.

In Objective-C, the most common implementation for such a class is by using a dispatch_once, where the code inside the block will only be run once.

+ (instancetype)sharedInstance {
static MySingletonClass *_sharedInstance = nil;
static dispatch_once_t oncePredicate;
dispatch_once(&oncePredicate, ^{
_sharedInstance = [[self alloc] initSingletonObject];
});
return _sharedInstance;
}

As documented:

If called simultaneously from multiple threads, this function waits synchronously until the block has completed.

With this, we can be sure, we could access our singleton instance from this sharedInstance method as expected, even in a multi-threading situation.

When every team member who is involved in the related project aware of the sharedInstance method we provided, there won’t be a problem. But sometimes, we could not expect everyone will read the class’s initialization methods and find a proper one before using it.

And in Objective-C, it’s quite often that we create our class to inherit NSObject directly/indirectly, which makes our class has the init method from NSObject.

This means, even if we already provided that sharedInstance method, nobody could stop other people to make another new…

--

--