Wednesday, June 12, 2013

IOS: the correct way to create object-c singleton

There are many wrong ways to create singleton class on the web, there is the right way to create it.

//  MyManager.h
#import

@interface MyManager : NSObject

+ (MyManager*) sharedManager;


@end



//  MyManager.m
#import "MyManager.h"

@implementation MyManager

static  MyManager* sharedInstance = nil;

+ (MyManager*) sharedManager {
    if(sharedInstance==nil) {
        @synchronized(self) {
            if (sharedInstance==nil) {
                sharedInstance = [[MyManager alloc] init];
            }
        }
    }
    return sharedInstance;
}

- (id)init {
    if (self = [super init]) {
        //init some properties here
    }
    return self;
}



@end


No comments: