GCD will guarantee that your singleton only gets instantiated once, even if called from multiple threads. Insert this into any class for a singleton instance called shared
.
+ (instancetype)shared {
// Variable that will point to the singleton instance. The `static`
// modifier makes it behave like a global variable: the value assigned
// to it will "survive" the method call.
static id _shared;
static dispatch_once_t _onceToken;
dispatch_once(&_onceToken, ^{
// This block is only executed once, in a thread-safe way.
// Create the instance and assign it to the static variable.
_shared = [self new];
});
return _shared;
}