Singletons in Objective-C

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:

Leave a Reply

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