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.


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *