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:
- http://getsetgames.com/2009/08/30/the-objective-c-singleton/
- http://www.duckrowing.com/2010/05/21/using-the-singleton-pattern-in-objective-c/
There's also some good discussion on singletons here: