Quick tip: using singleton pattern

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:

@interface MySingleton : NSObject
+ (MySingleton *)sharedInstance;

in MySingleton.m file:

+ (MySingleton *)sharedInstance
    static MySingleton *sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[self alloc] init];
    return sharedInstance;
    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:

NSString* someString = [[MySingleton sharedInstance] someMethodReturningString];

Leave a Reply