Skip to content

Instantly share code, notes, and snippets.

@cmkilger
Created May 26, 2011 21:18
Show Gist options
  • Save cmkilger/994111 to your computer and use it in GitHub Desktop.
Save cmkilger/994111 to your computer and use it in GitHub Desktop.
Singleton pattern
#import <Foundation/Foundation.h>
@interface SingletonClass : NSObject
+ (SingletonClass *) sharedInstance;
@end
#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