Skip to content

Instantly share code, notes, and snippets.

@huobazi
Created November 16, 2011 05:37
Show Gist options
  • Save huobazi/1369367 to your computer and use it in GitHub Desktop.
Save huobazi/1369367 to your computer and use it in GitHub Desktop.
Objective-c singleton
//from http://boredzo.org/blog/archives/2009-06-17/doing-it-wrong
@interface SingletonManager : NSObject {}
+ (id)sharedManager;
@end
static SingletonManager *sharedInstance = nil;
@implementation SingletonManager
#pragma mark -
#pragma mark Singleton
+ (void)initialize{
if(!sharedInstance){
[[[self alloc] init] release];
}
}
+ (id)sharedManager{
return sharedInstance;
}
+ (id)allocWithZone:(NSZone *)zone{
return [sharedInstance retain] ?: [super allocWithZone:zone];
}
- (id)init{
if(!sharedInstance){
if ((self = [super init])){
//initialize ivars
}
sharedInstance = [self retain];
}else if(self != sharedInstance){
[self release];
self = [sharedInstance retain];
}
return self;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment