So far I saw many examples, but not every of them is valid, follow my rules and you will get proper singleton pattern.
in MySingleton.h file:
1 2 3 4 5 |
@interface MySingleton : NSObject { } + (MySingleton *)sharedInstance; -(id)init; |
in MySingleton.m file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
+ (MySingleton *)sharedInstance { static MySingleton *sharedInstance = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ sharedInstance = [[self alloc] init]; }); return sharedInstance; } -(id)init{ if ((self=[super init]) ) { // put your init code here } return self; } |
And thats all. The key is to use dispatch_once which will guarantee code inside will be executed only once per whole app lifetime. You can use it like this:
1 |
NSString* someString = [[MySingleton sharedInstance] someMethodReturningString]; |