Skip to content

Instantly share code, notes, and snippets.

@rebelzach
Created October 27, 2010 18:45
Show Gist options
  • Save rebelzach/649677 to your computer and use it in GitHub Desktop.
Save rebelzach/649677 to your computer and use it in GitHub Desktop.
An Objective-C template for singleton classes
static MySingleton *sharedInstance = nil;
@implementation MySingleton
#pragma mark -
#pragma mark class instance methods
#pragma mark -
#pragma mark Singleton methods
+ (MySingleton*)sharedInstance
{
@synchronized(self)
{
if (sharedInstance == nil)
sharedInstance = [[MySingleton alloc] init];
}
return sharedInstance;
}
+ (id)allocWithZone:(NSZone *)zone {
@synchronized(self) {
if (sharedInstance == nil) {
sharedInstance = [super allocWithZone:zone];
return sharedInstance; // 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;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment