Created
December 20, 2012 08:24
-
-
Save meadlai/4343783 to your computer and use it in GitHub Desktop.
Singleton Instance in Objective-C
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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