Generic sharedInstance iOS implementation

One very common pattern when implementing Objective C singleton objects is the sharedInstance method.

Because I was a bit tired of repeating this code in several of my classes I decided to implement a Xcode Code Snippet that can be reused everywhere.

+ (instancetype) sharedInstance {
    static id _sharedInstance = nil;
    static dispatch_once_t _onceToken;
    dispatch_once(&_onceToken, ^{
        _sharedInstance = [[self alloc] init];
    });
    
    return _sharedInstance;
}

As you can see simple code that can be apply to any object.

Published by Sérgio Estêvão

Hello my name is Sérgio and I’m an experienced Mobile Software Architect living in Edinburgh.

Leave a comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: