Skip to content

Instantly share code, notes, and snippets.

@meadlai
Created December 20, 2012 08:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save meadlai/4343783 to your computer and use it in GitHub Desktop.
Save meadlai/4343783 to your computer and use it in GitHub Desktop.
Singleton Instance in Objective-C
#pragma mark
#pragma mark Singleton Instance--
static AppManager *sharedSingleton_ = nil;
// Get the shared instance and create it if necessary.
+ (AppManager *) sharedInstance{
if (sharedSingleton_ == nil){
@synchronized(self){
//double checking.
if (sharedSingleton_ == nil) {
sharedSingleton_ = [NSAllocateObject([self class], 0, NULL) init];
}
}
}
return sharedSingleton_;
}
// We don't want to allocate a new instance, so return the current one.
+ (id) allocWithZone:(NSZone *)zone{
//return instance
return [[self sharedInstance] retain];
}
// Equally, we don't want to generate multiple copies of the singleton.
- (id) copyWithZone:(NSZone*)zone{
return self;
}
//
- (id) retain{
return self;
}
- (NSUInteger) retainCount{
// denotes an object that cannot be released
return NSUIntegerMax;
}
// This function is empty, as we don't want to let the user release this object.
- (oneway void)release {
}
//Do nothing, other than return the shared instance - as this is expected from autorelease.
- (id)autorelease {
return self;
}
// Your dealloc method will never be called, as the singleton survives for the duration of your app.
// However, I like to include it so I know what memory I'm using (and incase, one day, I convert away from Singleton).
-(void)dealloc{
[super dealloc];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment