September 14, 2016 Andrey

Singleton in iOS

Recommended way of creating singleton according to Apple is in the following way:

+ (AKMySingleton *)sharedInstance {
    
    static AKMySingleton *_sharedInstance = nil;
    static dispatch_once_t onceToken;
    
    dispatch_once(&onceToken, ^{
        _sharedInstance = [[[self class] alloc] init];
    });
    
    return _sharedInstance;
}

Dispatch-once is a synchronous operation that will make sure that there are no multiple threads that are trying to allocate and instantiate singleton.