Dead simple singleton implementation

Over the times I made plenty of exotic singleton implementations, but lately I started to use this lightweight structure. Simply a class holds a static pointer, and whenever you create an instance, it will be assigned to that pointer. You can access it via a single class method.

In terms of code it needs a class method to access the global instance.

@interface APPConfiguration : NSObject

+(APPConfiguration*)sharedInstance;

@end

In the implementation you just create a static reference, and populate it once client invokes init on an instance.

__strong static APPConfiguration *_sharedInstance = nil;

@implementation APPConfiguration

+(APPConfiguration*)sharedInstance
{ return _sharedInstance; }

-(id)init
{
    if (self = [super init])
    {
        // Reference.
        _sharedInstance = self;
    }
    return self;
}

@end

There you go. It is simple enough to not create a base class for this, but implement this quiet a few boilerplate in every class you want to be singleton.

This method is not suitable for subclassing, as subclasses’ reference would overwrite superclass references. This is really to be lightweight, or on the go solution. Also this not prevent clients to overwrite the sole instance, so it could be designed to be safer, but that is not the point here.

DISCLAIMER. THE INFORMATION ON THIS BLOG (INCLUDING BUT NOT LIMITED TO ARTICLES, IMAGES, CODE SNIPPETS, SOURCE CODES, EXAMPLE PROJECTS, ETC.) IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE INFORMATION ON THIS BLOG (INCLUDING BUT NOT LIMITED TO ARTICLES, IMAGES, CODE SNIPPETS, SOURCE CODES, EXAMPLE PROJECTS, ETC.).

Become a Patron!