Created
June 9, 2013 23:04
-
-
Save chris-erickson/5745636 to your computer and use it in GitHub Desktop.
This is a preferred way to set up a singleton.
This file contains hidden or 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 | |
{ | |
} | |
// Properties of the singleton | |
+(SingletonClass *)sharedSingleton; | |
@end |
This file contains hidden or 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" | |
@implementation SingletonClass | |
static SingletonClass *theSingleton = nil; | |
+(SingletonClass *)sharedSingleton { | |
if (theSingleton != nil) { | |
return theSingleton; | |
} | |
static dispatch_once_t onceToken; | |
dispatch_once(&onceToken, ^{ | |
theSingleton = [[SingletonClass alloc] init]; | |
}); | |
return theSingleton; | |
} | |
// Called the first time the Singleton is used | |
- (id)init | |
{ | |
self = [super init]; | |
if (self) { | |
// Post initialization code such as setting other properties | |
} | |
return self; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment