Sunday, October 11, 2009

Apple singleton implementation

This is Apple code recomendation for creating a singleton


static MyGizmoClass *sharedGizmoManager = nil;

+ (MyGizmoClass*)sharedManager{
@synchronized(self) {
if (sharedGizmoManager == nil) {
[[self alloc] init]; // assignment not done here
}
}
return sharedGizmoManager;
}

+ (id)allocWithZone:(NSZone *)zone{
@synchronized(self) {
if (sharedGizmoManager == nil) {
sharedGizmoManager = [super allocWithZone:zone];
return sharedGizmoManager; // assignment and return on first allocation
}
}
return nil; //on subsequent allocation attempts return nil
}

- (id)copyWithZone:(NSZone *)zone{
return self;
}

- (id)retain{
return self;
}

- (unsigned)retainCount{
return UINT_MAX; //denotes an object that cannot be released
}

- (void)release{
//do nothing
}

- (id)autorelease{
return self;
}