Danny's Lab

Engineering the World

Singletons in Objective-C

Published on: Nov 15, 2010
Reading time: 0 minutes

Here's the fullest implementation of a Singleton pattern for Objective-C.

Credit where due. I did not write this code, just repeating here for convenience. See below for source.

static MyGizmoClass *sharedGizmoManager = nil; + (MyGizmoClass*)sharedManager { @synchronized(self) { if (sharedGizmoManager == nil) { [[MyGizmoClass alloc] init]; } } return sharedGizmoManager; } + (id)allocWithZone:(NSZone *)zone { @synchronized(self) { if (sharedGizmoManager == nil) { return [super allocWithZone:zone]; } } return sharedGizmoManager; } - (id)init { Class myClass = [self class]; @synchronized(myClass) { if (sharedGizmoManager == nil) { if (self = [super init]) { sharedGizmoManager = self; // custom initialization here } } } return sharedGizmoManager; } - (id)copyWithZone:(NSZone *)zone { return self; } - (id)retain { return self; } - (unsigned)retainCount { return UINT_MAX; } - (void)release {} - (id)autorelease { return self; }

This example was taken from here:

There's also some good discussion on singletons here: