Created
May 26, 2011 21:18
-
-
Save cmkilger/994111 to your computer and use it in GitHub Desktop.
Singleton pattern
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
#import <Foundation/Foundation.h> | |
@interface SingletonClass : NSObject | |
+ (SingletonClass *) sharedInstance; | |
@end |
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
#import "SingletonClass.h" | |
static SingletonClass * sharedInstance = nil; | |
@interface SingletonClass () | |
- (id) initPrivately; // We don't override init, which can be called externally | |
@end | |
@implementation SingletonClass | |
+ (SingletonClass *) sharedInstance { | |
static dispatch_once_t onceToken; | |
dispatch_once(&onceToken, ^{ | |
sharedInstance = [[super allocWithZone:nil] initPrivately]; | |
}); | |
return sharedInstance; | |
} | |
- (id)initPrivately { | |
if (!(self = [super init])) | |
return nil; | |
return self; | |
} | |
- (void)dealloc { | |
[super dealloc]; | |
} | |
#pragma mark - Singleton | |
// Methods that assist this class in acting as a singleton | |
+ (id)allocWithZone:(NSZone*)zone { return sharedInstance; } | |
- (id)copyWithZone:(NSZone *)zone { return self; } | |
- (id)retain { return self; } | |
- (NSUInteger)retainCount { return UINT_MAX; } | |
- (void)release {} | |
- (id)autorelease { return self; } | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment